Modules can be imported using the import statement. When a module is imported:
sys.modules)sys.meta_path: gets list of finders). Module is retrieved (loaded) from loaders (returned by finders). empty module typed object is created. A reference to the module is added to the system cache (sys.modules) and the module is compiled. When the module is executed, it sets up the module's namespaceModule Finders:
In [2]: sys.meta_pathOut[2]:[_frozen_importlib.BuiltinImporter, #--> finds built-ins, such as math_frozen_importlib.FrozenImporter, #--> finds frozen modules_frozen_importlib_external.PathFinder] #--> file-based modules
PathFinder: Finds file-based modules based on sys.path and package __path__
Module Properties: __spec__, __name__, __package__ (empty for modules), __file__ (found by PathFinder)
Modules may reside:
sys.path or in a path specified by <package>.__path__Packages are modules. They can contain modules, packages.
If a module is a package, then it must have a value set for `path
Packages represent a hierarchy of modules/packages
How to define package?: Directory name becomes package name & __init__.py is where the code for package will go.
If we don't have the __init__.py file, then Python will create an implicit namespace package
Package will have __path__ & __file__ property defined:
__path__ : file system directory path (absolute)__file__: file system path to __init__.py (absolute)Module will also have above properties:
__file__ : location of module code in file system__package__: package the module code is located in (is empty string if module is located in application root)__path__: only set if module is also a package. Location of the package (directory) in the file systemNested packages:
app/module.pypack1/__init__.pymodule1.pymodule2.pypack1_1/__init__.pymodule1_1a.pymodule1_1b.py
pack1: pack1.module1pack1: pack1.pack1_1pack1.pack1_1: pack1.pack1_1.module1_1amodule.__file__:.../app/module.pymodule:__path__: Not setmodule.__package__: ""pack1.__file__:.../app/pack1/__init__.pypack1.__path__: .../app/pack1/pack1.__package__: pack1sys.modules__all__: List of public objects of a module, as interpreted by import *. It overrides the default of hiding everything that begins with an underscore.
Example:
# date.py__all__ = ['is_date', 'constant', 'date_helper_1']constant = 3.14def is_date(arg): passdef date_helper_1(): passdef date_helper_2(): passdef constant(): pass'is_date', 'constant', 'date_helper_1' can be used. Other funcs are hidden.