How to Create a module in Python

Total Views : 284
Zoom In Zoom Out Read Later Print

This post will be about how you can create your own modules in python. so let's start.

A module is an importable file containing definitions and statements.

A module can be created by creating a .py file.

# hello.py
def say_hello():
 print("Hello!")

Functions in a module can be used by importing the module.

For modules that you have made, they will need to be in the same directory as the file that you are importing them into. (However, you can also put them into the Python lib directory with the pre-included modules, but should be avoided if possible.)

$ python
>>> import hello
>>> hello.say_hello()
=> "Hello!"

Modules can be imported by other modules.

# greet.py
import hello
hello.say_hello()

Specific functions of a module can be imported.

# greet.py
from hello import say_hello
say_hello()

Modules can be aliased.

# greet.py
import hello as ai
ai.say_hello()

A module can be a stand-alone runnable script.

# run_hello.py
if __name__ == '__main__':
 from hello import say_hello
 say_hello()
Run it!
$ python run_hello.py
=> "Hello!"

If the module is inside a directory and needs to be detected by python, the directory should contain a file named

__init__.py.

See More

Latest Photos