Any .py file is a module. The filename (without .py) is the module name.
"""Utility functions for string and math operations."""
__version__ = '1.0.0'
__all__ = ['format_name', 'add'] # Controls 'from utils import *'
# Public function
def format_name(first, last):
return f'{first} {last}'.title()
# Public function
def add(a, b):
return a + b
# Internal/Private function (by convention)
def _internal_helper():
pass
# Execution guard
if __name__ == '__main__':
print('Testing utils module...')
print(format_name('john', 'doe'))
print(add(2, 3))import utils
print(utils.format_name('alice', 'smith'))
print(utils.__version__)
# Or specific imports
from utils import format_name, add__all__ = ['public_func'] # Only these are imported with *
def public_func(): pass
def _private_func(): pass
def helper_func(): pass # Not in __all__, won't be imported with *
# Elsewhere:
# from utils import * # Only gets 'public_func'
print(my_module.__name__) # 'my_module'
print(my_module.__file__) # '/path/to/my_module.py'
print(my_module.__doc__) # Docstring of the module
print(dir(my_module)) # List all attributes# myproject/
# utils/
# __init__.py
# strings.py
# math_ops.py
# In strings.py:
from .math_ops import add # Relative import (same pkg)
from ..core import engine # Relative import (parent pkg)
from myproject.utils import x # Absolute importBest Practice: Use absolute imports in most cases. They are clearer and work even if the module is moved.,
python -m my_package.my_module # Runs module as scriptSince we are in a single file, simulate module creation. Create a string `module_code` that contains a proper module structure: a docstring, `__version__`, `__all__`, a public function `greet(name)`, and a private function `_log()`. Then, write a function `analyze_module_code(code_str)` that parses the string and returns a dict of found attributes: `has_docstring`, `has_version`, `has_all`, `public_functions` (list of 'def' names not starting with _).