Creating Modules

Code Containers

Function simplest form of code containers we discussed it before

Class is a collection of functions

Module is a file which contains various Python functions and global variables. It is simply just .py extension file which has python executable code.

Package is a collection of modules. It must contain an init.py file as a flag so that the python interpreter processes it as such. The init.py could be an empty file without causing issues.

Library is a collection of packages.

Framework is a collection of libraries. This is the architecture of the program.

What's Module

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 module.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 module

module.greeting("Ayman")

Output:
Hello, Ayman

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):

Save this code in a file named module.py

person = {
  "name": "John",
  "age": 36,
  "country": "Norway"
}

Import the module named mymodule, and access the person dictionary:

import module

a = mymodule.person["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:

import module as mx

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

check official documentation for all modules

Import From Module

You can choose to import only parts from a module, by using the from keyword.

from module import person

When importing using the from keyword, do not use the module name when referring to elements in the module. Example: person["age"], not mymodule.person1["age"]

Last updated