A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable name. For instance, use your favorite text editor to create a file called fibo.py in your project directory.
A module can define functions, classes, and variables. A module can also include runnable code. In this article, we will go over how to create and import modules in Python.
Writing Python modules is very easy. To create a module just save the code you want in a file with the file extension .py:
A module can be created by creating a hello.py file.
Code language: PHP (php)
# hello.py def hello_world(): print("Hello World!")
Before using a module, it must first be imported. To import a module type import followed by the name of the module:
imports the entire module and makes it available for use later in your program. If you only want certain functions or variables from a module, list their names after the import keyword:
from example_module import example_function, example_variable
The functions in a module can be used by importing the module.
Your own modules must be in the same directory as the import file.
You can alternatively place them in Python’s lib directory with pre-included modules, but it’s not recommended.
$ python >>> import hello >>> hello.hello_world() => "Hello World!"
If the module is inside a directory and needs to be detected by python, the directory should contain a file named __init__.py
That concludes our overview of how to create modules in Python. As you can see, they are relatively simple to put together and can be an extremely useful tool when coding larger projects composed of multiple files. Modules can help keep your code organized and prevent namespace issues from arising. Stay tuned for more blogs on interesting topics in computer science!