Module

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. ๐Ÿ™‚