Python Modules
Python Modules
What is a module?
• Consider a module to be the same as a code library.
• 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
• 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
• Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
• You can name the module file whatever you like, but it must have the
file extension .py
Re-naming a Module
• You can create an alias when you import a module, by using the as
keyword
• Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
Import From Module
• You can choose to import only parts from a module, by using the from
keyword
• The module named mymodule has one function and one dictionary
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
• Import only the person1 dictionary from the module:
print (person1["age"])
Note: When importing using the from keyword, do not use the module
name when referring to elements in the module. Example:
person1["age"] not mymodule. person1["age"])