Home >Backend Development >Python Tutorial >How to Handle Relative Imports in Python Packages When Running Modules as Scripts?
When attempting to import a function from another file in the same directory, using either from .mymodule import myfunction or from mymodule import myfunction can result in errors. The reason lies in whether the module containing the function being imported is inside a package or not.
Relative imports work when the module is inside a package. To create a package, an __init__.py file must be present in the directory containing the modules. However, it's also important to ensure the module can be run as a script sometimes.
A common layout for a package containing multiple modules and a main script is as follows:
mypackage/
Within mymodule.py:
# Exported function def as_int(a): return int(a) # Test function for module def _test(): assert as_int('1') == 1 if __name__ == '__main__': _test()
Within myothermodule.py:
# Import exported function from the mymodule from .mymodule import as_int # Exported function def add(a, b): return as_int(a) + as_int(b) # Test function for module def _test(): assert add('1', '1') == 2 if __name__ == '__main__': _test()
Within main.py:
# Import exported function from myothermodule from mypackage.myothermodule import add def main(): print(add('1', '1')) if __name__ == '__main__': main()
When running main.py or mypackage/mymodule.py, the code executes without issues. However, attempting to run mypackage/myothermodule.py results in an error related to the relative import used (from .mymodule import as_int).
There are two alternative approaches to address this:
The above is the detailed content of How to Handle Relative Imports in Python Packages When Running Modules as Scripts?. For more information, please follow other related articles on the PHP Chinese website!