Python Modules


What is a Module?

Consider the module to match the code library.

A file containing a set of tasks that you want to include in your application.


Create a Module

To create a module simply save the code you want to a file with the .py file extension:


Example

Save this code in a file named mymodule.py

def greeting(name):
  print("Hello, " + name)

Use a Module

We can now use the newly created module, using the import statement:


Example

Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Note: If you are using a module function, use the syntax: module_name.function_name.



Variables in Module

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


Example

Save this code in the file mymodule.py

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


Example

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

import mymodule

a = mymodule.person1["age"]
print(a)


Naming a Module

You can compose a module file or whatever you like, but it should have a .py file extension

Re-naming a Module

You can create a noun when importing a module, using 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 modules built into Python, which you can download whenever you like.


Example

Import and use the platform module:

import platform

x = platform.system()
print(x)


Using the dir() Function

There is a built-in function to list all the job names (or variable names) in the module. dir() function:


Example

List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Note: The dir () function can be applied to all modules, including the ones you created.



Import From Module

You can choose to import only module components, using the keyword from.


Example

The module named mymodule has one function and one dictionary:

def greeting(name):
  print("Hello, " + name)

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


Example

Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Note: If you enter using a from keyword, do not use the module name when referring to module items. Example: person1 ["years"], not mymodule.person1 ["years"]