Modules
Modules
A file containing a set of functions you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a module
Now we can use the module we just created, by using the import
statement
Example
Import the module named mymodule, and call the greeting function
import mymodule
mymodule.greeting("Bhavya")
Variables in module
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc)
Example
Save this code in the file mymodule.py
person = {
"name": "Bhavya",
"age": 29,
"country": "India"
}
Import the module named mymodule, and access the person dictionary
import mymodule
a = mymodule.person1["name"]
print(a)
Output:
Bhavya
Re-naming a module
We can create an alias when you import a module, by using the as keyword
Example
Create an alias for mymodule called mx
import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
There are several built-in modules in Python, which we can import whenever you like.
Example
Import and use the platform module
import platform
x = platform.system()
print(x)
Output:
Linux
Using the dir() function
The dir() function lists all the function names or variable names in a module.
Example
import platform
x = dir(platform)
print(x)
Import From Module
We can choose to import only parts from a module, by using the from keyword.
Example
mymodule.py
def greeting(name):
print("Hello, " + name)
person = {
"name": "Bhavya",
"age": 29,
"country": "India"
}
Import only the person dictionary from the module.
from mymodule import person1
print (person["name"])
Output:
Bhavya