Python Module Attributes: Understanding __name__ and More
Learn about the attributes of Python modules, including the __name__
attribute which returns the name of the module. This guide provides an overview of useful module attributes and how they can be used to access information about modules in Python.
Python Module Attributes
Python modules have several attributes that describe them or provide useful information about the module.
__name__ Attribute
The __name__
attribute returns the name of the module.
Example: __name__ Attribute
import math
print(math.__name__) # 'math'
In a custom module, such as calc
:
Example: __name__ Attribute
import calc
print(calc.__name__) # 'calc'
Modifying the __name__
attribute:
Example: Set __name__
def SayHello(name):
print("Hi {}! How are you?".format(name))
__name__ = "SayHello"
__doc__ Attribute
The __doc__
attribute holds the documentation string (docstring) of the module.
Example: __doc__ Attribute
import math
print(math.__doc__)
__file__ Attribute
The __file__
attribute holds the file path of the module.
Example: __file__ Attribute
import io
print(io.__file__) # Output: 'C:\\python37\\lib\\io.py'
__dict__ Attribute
The __dict__
attribute returns a dictionary of all attributes and functions in a module.
Example: __dict__ Attribute
import math
print(math.__dict__)
Using the dir() Function
The dir()
function lists all attributes and functions in a module.
Example: dir() Function
import math
print(dir(math))