What are Modules in Python?
Modules are simply a ‘program logic’ or a ‘python script’ that can be used for variety of applications or functions. We can declare functions, classes etc in a module.
A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.
How To Create Modules In Python?
Creating a module in python is similar to writing a simple python script using the .py extension. For the above example lets try to make a module for the various operations.
1 2 3 4 5 6 7 8 9 10 11 | def add(x,y): return x + y def sub(x, y): return x - y def prod(x, y): return x * y def div(x, y): return x / y |
Save the above code in a file Calc.py. This is how we create a module in python. We have created different functions in this module. We can use these modules in our main file, lets take a look at how we are going to use them in a program.
How To Use Python Modules?
We will use the import keyword to incorporate the module into our program, from keyword is used to get only a few or specific methods or functions from a module. Lets see what are different methods to use a module in your program.
Lets say we have our file with a name main.py.
1 2 3 4 5 6 | import calc as a a = 10 b = 20 addition = a.add(a,b) print (addition) |
In the above code, we have created an alias using the as keyword. The output of the above code will be the addition of the two numbers a and b using the logic specified in the add function in the calc.py module.
Lets take a look at another approach.
1 2 3 4 5 | from calc import * a = 20 b = 30 print (add(a,b)) |
In the above code, we have imported all the functions using the asterisk and we can simply mention the function name to get the results.
Python Module Path
When we import a module, the interpreter looks for the module in the build-in modules directories in sys.path and if not found, it will look for the module in the following order:
- Current directory
- PYTHONPATH
- Default directory
1 2 3 | import sys print (sys.path) To add Your file path to the system path.You can use m_directory="home/python_files" sys.path.append(m_directory) # |
When you run the above code, you will get the list of directories. You can make changes in the list to create your own path.
Comments
Post a Comment