A module is like a code library that stores importable code. It can contain functions as well as variables of all types (arrays, dictionaries, objects etc.). There are several built-in modules in Python, which you can import whenever required. You may also create modules such as the one shown here.
To create a module, save the code you want in a file with the .py
extension. For example, you can create module “mymodule.py” by saving the following code which contains a function named “greeting” and a dictionary named “person” into a file named “mymodule.py”.
def greeting(name):
print("Hello, " + name)
person = {
"name": "John",
"age": 36,
"country": “Singapore"
}
Having created module “mymodule”, you may import it using the import
command to access def “greeting” and the “person” dictionary:
import mymodule
name = mymodule.person["name"]
mymodule.greeting(name)
Hello, John
In Python you can create an alias for a module. For instance, the following code uses the alias “mx” for “mymodule”:
import mymodule as mx
print(mx.person["name"])
John
Some modules can be quite large and it may impair performance if you import the entire library. In such cases you may choose to import only the functions or variables that you require. For instance, in the following code only the “person” dictionary is imported from “mymodule”:
from mymodule import person
print (person["age"])
36
Use the Search Bar to find content on MarketingMind.
Contact | Privacy Statement | Disclaimer: Opinions and views expressed on www.ashokcharan.com are the author’s personal views, and do not represent the official views of the National University of Singapore (NUS) or the NUS Business School | © Copyright 2013-2025 www.ashokcharan.com. All Rights Reserved.