Modules and Packages
As programs grow, you need to organize code into separate files. Modules are `.py` files containing Python code. Packages are directories containing modules and a special `__init__.py` file. Modules and packages allow code reuse and better project structure.
Creating and Importing Modules
Create a file `mymodule.py` with some functions. Then import it in another file.
# mymodule.py
def greet(name):
return f"Hello, {name}!"
# main.py
import mymodule
print(mymodule.greet("Alice"))
Import Variants
- `import module` – use `module.function()`
- `from module import function` – use `function()` directly
- `import module as alias` – alias for convenience
- `from package.subpackage import module` – nested imports
Packages
A package is a directory with an `__init__.py` file (can be empty). For example:
mypackage/
__init__.py
module1.py
module2.py
The `__name__` Variable
When a script is run directly, `__name__` is `"__main__"`. This allows code to be executed only when the script is run, not when imported.
if __name__ == "__main__":
print("This runs only when executed directly.")
Two Minute Drill
- Modules are `.py` files; packages are directories with `__init__.py`.
- Import modules with `import` or `from ... import ...`.
- Use `as` to alias module names.
- Condition `if __name__ == "__main__"` guards code from running on import.
- Organizing code into modules/packages improves maintainability.
Need more clarification?
Drop us an email at career@quipoinfotech.com
