This article will cover 4 Cases of Import:
- Everything from module in package
2. Certain functions from py file in package
3. py file at same level (relative import)
4. using __all__ with import *
Create a folder structure as below
first_pkg is the module to import , there are 2 services inside and 1 lib file . all __init__.py are empty
import everything from service1 but only api1 and api2
service1.pydef api1(): print('api1')def api2(): print('api2')def internal(): print('internal func')__all__ = ["api1","api2"]
first_pkg_test.pyfrom first_pkg.api.service1 import *if __name__ == “__main__”: api1() api2() #internal() #this will throw error
Import certain functions from service2 and lib
service2.py
def api3(): print('api3')
first_pkg_test.pyimport first_pkg.api.service2 as service2if __name__ == "__main__": service2.api3()
lib.pydef lib1(): print('lib1')
first_pkg_test.pyimport first_pkg.lib as libif __name__ == "__main__": lib.lib1()
Import same level py file
first_pkg_lib.pydef pkg_lib_outside(): print('pkg lib outside')
first_pkg_test.pyfrom first_pkg_lib import pkg_lib_outsideif __name__ == "__main__": pkg_lib_outside()
Consolidate everything into package level export and import *
__init__.py file (under first_pkg) :
from .lib import lib1from .api.service1 import api1, api2from .api.service2 import api3__all__ = ['lib1','api1','api2','api3']
In first_pkg_test.pyfrom first_pkg import *if __name__ == "__main__":lib1()api1()api2()api3()
Make module executable from python command
add __main__.py in first_pkg folder .
Load modules by string name
In __main__.py , we can load some modules by passing string name . this could be useful when the module name is dynamically computed
print('package1 loaded')import importlibservice = importlib.import_module('api.service1')service.api1()
Now run the package
Python3 first_pkg