9. Module#
A module is a importable python file and can be created by creating a file with extension as .py
We can import the objects present in the module.
In the below ๐ example, we are importing hello
function from greet
module (greet.py)
greet.py
"""Module to greet the user"""
import getpass
def hello():
"""Greets the user."""
username: str = getpass.getuser().capitalize()
print(f"Hello {username}. Have a great day :)")
if __name__ == "__main__":
hello()
from greet import hello
hello()
Hello Naveen. Have a great day :)
letโs have a look at the greet.py module.
Well, we see the below if
condition.
if __name__ == "__main__":
hello()
But why do we we need to have it๐ค? We can just call the hello
function at the end as
hello()
Letโs see the below๐ code to know why we use the first approach rather than the second.๐
import greet
๐ The above code doesnโt greet you ๐ข
%run ./greet.py
Hello Naveen. Have a great day :)
But, this above code greets you๐.
The reason for this is, in the first snippet, we are importing a module called greet
, so the actual code we are executing is in this REPL or Ipython shell.
Coming to second snippet, we are executing the greet.py
directly.
Value of __name__
would be โ__main__โ if we are executing a Python module directly. If we import a module(using the module indirectly) then value of __name__
would be the relative path of the imported module. In the first example the __name__
in the greet module would be โgreetโ. As the โgreetโ is not equal to โ__main__โ, thatโs the reason, we never went to the if
condition when we imported greet module. ๐