I am running Python 2.5.
This is my folder tree:
ptdraft/ nib.py simulations/ life/ life.py
(I also have __init__.py
in each folder, omitted here for readability)
How do I import the nib
module from inside the life
module? I am hoping it is possible to do without tinkering with sys.path.
Note: The main module being run is in the ptdraft
folder.
In order to import a module, the directory having that module must be present on PYTHONPATH. It is an environment variable that contains the list of packages that will be loaded by Python. The list of packages presents in PYTHONPATH is also present in sys. path, so will add the parent directory path to the sys.
Importing module from a package We can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it. Now we can directly call this function.
With your new skills, you can confidently import packages and modules from the Python standard library, third party packages, and your own local packages. Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long.
You could use relative imports (python >= 2.5):
from ... import nib
(What’s New in Python 2.5) PEP 328: Absolute and Relative Imports
EDIT: added another dot '.' to go up two packages
Relative imports (as in from .. import mymodule
) only work in a package. To import 'mymodule' that is in the parent directory of your current module:
import os import sys import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) import mymodule
edit: the __file__
attribute is not always given. Instead of using os.path.abspath(__file__)
I now suggested using the inspect module to retrieve the filename (and path) of the current file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With