We know how to create a Python file. But did you know that Python files have two faces?
- If you create a single Python file to perform some tasks, that’s called a script.
- If you create a Python file specifically to store functions, classes, and other definitions, that’s called a module.
We use modules by importing from them, using the Python
import statement which will be our next topic.
So a module is a file that contains Python code, ending with the
.py extension. In other words: any Python file is also a module. The name of a module is the same as the file name, excluding the extension. For example, if you create a file named
mymodule.py, the name of your module is
Why do you need Python modules?
Modules have a lot to offer:
- They allow us to organize code. For example, you could store all functions and data related to math in a module called ‘math.py’. This is exactly what Python does in the math module!
- We can reuse code more easily. Instead of copying the same functions from one file to the next or even from one project to the next, we can now reuse the module instead. And if we properly package the module, we can even share it with others in the Python community.