Python Modules Tutorial
1. Introduction to Modules
A module is a file consisting of Python code. It can define functions, classes, and variables that you can use in your own Python scripts. You use the `import` statement to include the functionality from the module.
import math
2. Accessing Module Functions
You can access functions in a module using the dot operator.
print(math.sqrt(25))
3. Importing Specific Functions
If you only need a specific function from a module, you can import just that function using the `from` keyword.
from math import sqrt print(sqrt(25))
4. Aliasing Modules
Sometimes module names can be long, making your code harder to read. Python allows you to alias module names when you import them using the `as` keyword.
import math as m print(m.sqrt(25))
5. Using Multiple Functions from a Module
Modules can contain many functions. You can import and use multiple functions from the same module.
from math import sqrt, factorial print(sqrt(25)) print(factorial(5))
6. Understanding the Module Search Path
When you import a module, Python searches a list of directories defined in `sys.path`. The search starts from the current directory.
import sys print(sys.path)
7. Adding to the Module Search Path
You can add a new directory to the module search path using `sys.path.append()`.
sys.path.append('/path/to/directory')
8. Creating Your Own Module
You can create your own Python module by creating a new .py file. For example, let’s say you have a file `mymodule.py` with the following code:
# mymodule.py def hello_world(): return "Hello, World!"
9. Importing Your Own Module
You can import your own module just like you would import a built-in Python module.
import mymodule print(mymodule.hello_world())
10. Reloading a Module
If a module has been edited and you want to run a script with the updated version of the module, you need to reload it using `importlib.reload()`.
import importlib importlib.reload(mymodule)