Python statements (code in general) are usually written in files which are stored in folders.
A file containing Python code is a module (or a script, if we invoke the module directly from the shell). Modules contain classes, functions, variables and executable statements.
A directory (folder) containing modules and other directories, is a package.
Lets see how to organize our code and how to use it.
In [ ]:
!cat my_python_module.py
From Python, modules are invoked using import
(notice that when a module is imported, the code of the module is run):
In [ ]:
import my_python_module
However, this happens only the first time we invoke a module from another module (this notebook):
In [ ]:
import my_python_module # This import should not generate any output
Module structures are accesible from the invoker code using the notation: <module_name>.<structure>
:
In [ ]:
my_python_module.a
The module name of a module is accesible through the global variable __name__
:
In [ ]:
my_python_module.__name__
In [ ]:
!python my_python_module.py
In [ ]:
dir(my_python_module)
In [1]:
!tree my_package
In [2]:
!cat my_package/__init__.py
In [3]:
!cat my_package/my_module.py
my_package
as a module:
In [4]:
import my_package
In [ ]:
dir(my_package)
In [ ]:
my_package.my_module.a
In [ ]:
my_module.a # This should fail
In [ ]:
from my_package import my_module
In [ ]:
my_module.a # This should work
__main__.py
file with the first code to be executed:
In [ ]:
!cat my_package/__main__.py
In [ ]:
!python my_package
By default, modules and packages are imported from:
In [ ]:
import sys
sys.path
(Note: the previous output depends on the interpreter, the host, the configuration of Python, etc.)
To add a new directory, we can modify the PYTHONPATH
environment variable (from the shell):
In [ ]:
!python -c 'import sys; print(sys.path)'
!(export PYTHONPATH=$PYTHONPATH:'/my/new/dir'; python -c 'import sys; print(sys.path)')
(... or from Python itself):
In [ ]:
sys.path
In [ ]:
sys.path.append("/my/new/dir")
In [ ]:
sys.path