|
Single Py Files Containing
|
Python components you have defined (functions, variables, classes, etc.) Runnable code (scripts)
|
|
Can be:
|
Executed (python my_module.py) Imported from a shell or another file
|
|
IMPORTING
|
|
|
When you import a module, a new name, 'bound' to the module, is created in the current scope:
|
import math
x = math.pow(2, 3) |
|
from math import pow
x = pow(2, 3) |
|
|
We can also import a specific function from the module, and so now we don't need to specify the module name
|
from math import *
x = pow(2, 3) |
|
We could also achieve this by importing all objects in the module, but isk creating namespace conflicts:
|
from math import *
x = pow(2, 3) |
|
We can import a module under an alias to bind it to a name of our choice:
|
import pandas as pd import seaborn as sns
|
|
All runnable code in a module is executed at import.
|
|
|
f you want it to be executed only when you run the file, use the following:
|
|
|
if __name__ == "__main__":
print("This will be run only if the file is execut ed") |
__name__ is a special built-in variable which will automatically be set to "__main__" if the source file is being executed as the main program, rather than being imported.
|
|
When importing, Python looks for the module with the same name in:
|
|
|
The built-in modules
|
The directories defined in the sys.path list:
|
|
The current working directory
The PYTHONPATH list The default Python directory |
|
|
You can access this list at runtime and append new paths to it manually:
|
import sys print(sys.path) sys.path.append("/path/to/add")
|
|
from NameOfModule import NameOfFunction
|
from math import pow2
|
|
Packages are directories that contain modules and/or other packages. This can be a good way to group modules in a hierarchical directory structure.
|
|
|
__init__.py in a package will be executed at import.
|
Can be used to import nested modules at a higher level of hierarchy
|
|
When working with packages, it is recommended to assume code will be run from the top level and use absolute imports from there
|
|
|
Add an extra level of hierarchy and a setup.py file
|
To install run: pip install my_package/ (the / is important)
|
|
Once installed, you can import your module from Python, or run an executable in the shell if you've defined an entrypoint.
|
|
No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.