Module and Package Python


Modified:   November 11, 2017
Published:   November 12, 2017

Tags:

Modules

These are simple python files with the .py extension, which implement a set of functions/functionality. Modules are imported from other modules using the import command like import file Above will import variables/funtions/classes from file.py.

Packages

  • A package is a directory that contains multiple Python modules and must include an init.py file.

  • The init.py file marks the directory as a package and can also execute initialization code.

  • Even though modules and packages are conceptually different (file vs directory), both are of type ‘module’ when imported in Python:

    1
    2
    3
    4
    5
    6
    
    >>> import some_module
    >>> type(some_module)
    <type 'module'>
    >>> import some_package
    >>> type(some_package)
    <type 'module'>
    
  • When we import module we get all its functions, classes and variables defined in it.

  • When we import package only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules.

  • The directory to be identified as package by python, should have init.py file in that directory

  • Packages can have sub-packages, those directories should have init.py file in the sub-directory.



Let me know if you have any questions or comments.
It will help me to improve/learn.


< Older   Further Reading   Newer >