Looking for python Answers? Try Ask4KnowledgeBase
Looking for python Keywords? Try Ask4Keywords

Python Language Creating a module


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():

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

Specific functions of a module can be imported.

# greet.py
from hello import say_hello

Modules can be aliased.

# greet.py
import hello as ai

A module can be stand-alone runnable script.

# run_hello.py
if __name__ == '__main__':
    from hello import 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.