Package
Package is a directory containing modules and sub directories
Empty __init__.py
#__init__.py is empty
import myPackage
myPackage.m1.f_1() # Error, myPackage has no module m1
import myPackage.m1 # myPackage.* is not allowed here, import myPackage.m1
myPackage.m1.f_1()
#import myPackage.m1.f_1, not allowed to import function
import myPackage.m1 as m # rename imported module, import m, no myPackage
m.f_1()
from myPackage import m1 # import m1, no myPackage
m1.f_1()
from myPackage.m1 import f_1 # import f_1, no myPackage and m1
f_1()
Import functions to its parent namespace
#__init__.py
#from m1 import f_1 # not allowed in Python 3
from myPackage.m1 import f_1, f_2 # #access module from the root of the package
import myPackage # import myPackage.m1 and myPackage.f_1
myPackage.f_1()
myPackage.m1.f_1()
from myPackage import * # import m1 and f_1 to the current namespace
f_1()
m1.f_1()
from myPackage import f_1 # import f_1
f_1()
__all__, the list of modules that should be imported by from myPackage import *
#__init__.py
__all__ = ['m1', 'f_1']
from myPackage.m1 import f_1, f_2
from myPackage.m2 import f_3
from myPackage import * # import m1 and f_1, not f_2 and f_3
Empty __init__.py
#__init__.py #1, empty
#__init__.py #2, empty
import myPackage.sub_1.m3 # import myPackage.sub_1.m3
myPackage.sub_1.m3.f_5()
import myPackage.sub_1.m3 as m # import m
m.f_5()
from myPackage.sub_1 import m3 # import m3
m3.f_5()
from myPackage.sub_1.m3 import f_5 # import f_5
f_5()
#__init__.py #1, empty
#__init__.py #2
from myPackage.sub_1.m3 import f_5, f_6
import myPackage.sub_1 as sub # import sub.f_5, sub.f_6, and sub.m3
sub.f_5()
from myPackage import sub_1 # sub_1.f_5, sub_1.f_6, sub_1.m3
sub_1.f_5()
from myPackage.sub_1 import f_5 # import f_5
f_5()
Recursive import functions to parent namespace
#__init__.py #1
from myPackage.m1 import f_1, f_2
from myPackage.m2 import f_3
from myPackage.sub_1 import f_5
#__init__.py #2
from myPackage.sub_1.m3 import f_5, f_6
import myPackage # import myPackage.f_1, myPackage.f_2, myPackage.f_3, myPackage.f_5, myPackage.m1, myPackage.m2, myPackage.sub_1
from myPackage import * # import f_1, f_2, f_3, f_5, m1, m2, sub_1
Intra-package References
absolute reference
# m5.py
#!/usr/bin/python
from myPackage.sub_1.m3 import f_5
def main():
f_5()
if __name__ == "__main__":
main()
Relative reference
# m5.py
#!/usr/bin/python
from .m3 import f_5
def main():
f_5()
if __name__ == "__main__":
main()
Inter-package References
absolute reference
#__init__.py #1, empty
#__init__.py #2, empty
#__init__.py #3, empty
#!/usr/bin/python
from myPackage.sub_1 import m3
def main():
m3.f_5()
if __name__ == "__main__":
main()
relative reference
#!/usr/bin/python
from ..sub_1 import m3
def main():
m3.f_5()
if __name__ == "__main__":
main()
Package is a directory containing modules and sub directories