Summary: in this tutorial, you’ll learn about what a python module is and understand how it works.
What is a python module #
So far, you learned that a module in Python is a file that contains Python code. In fact, everything in Python is an object, including a module.
When you import a module using the import statement, Python creates a new module object. For example, the following imports the math built-in module:
import mathPython creates a new variable called math that references a module object:
import math
print(math)The math is a variable that references a module object:
<module 'math' (built-in)>The module name is math. The type of the math module is the class module:
<class 'module'>If you look at the globals(), you’ll see the math variable in the global namespace:
import math
from pprint import pprint
pprint(globals())Output:
{'__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>,
'__doc__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__name__': '__main__',
'__package__': None,
'__spec__': None,
'math': <module 'math' (built-in)>,
'pprint': <function pprint at 0x0000023FE66491F0>}Since math is an object, you can access its attributes. For example, you can get the name of the math object using the __name__ attribute:
import math
print(math.__name__)Output:
mathAnd you can access all of the attributes of the math object via the __dict__ :
import math
from pprint import pprint
pprint(math.__dict__)Output:
'__doc__': 'This module provides access to the mathematical functions\n'
'defined by the C standard.',
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__name__': 'math',
'__package__': '',
'__spec__': ModuleSpec(name='math', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'),
'acos': <built-in function acos>,
...And you can use math as a regular variable. For example, you can set it to None:
math = NoneThis instructs Python to destroy the module object that the math variable references.
The math is an instance of the ModuleType:
import math
from types import ModuleType
pprint(isinstance(math,ModuleType))Output:
TrueThe math module is a built-in module. Let’s examine a non-built-in module.
Non-built-in module #
The abc module allows you to define abstract base classes. It is not a built-in module:
import abc
print(abc)Output:
<module 'abc' from 'C:\\Python\\lib\\abc.py'>The abc module is defined in lib\abc.py file in Python’s installation folder. Unlike the math module which is a built-in module.
The type of the abc is also module:
import abc
print(type(abc))Output:
<class 'module'>Like the math module, the abc is an instance of the ModuleType as shown in the following example:
import abc
from types import ModuleType
pprint(isinstance(abc,ModuleType))Output:
TrueSummary #
- A Python module is an object loaded from a file.
Thank you for your feedback!