Course Outline (Part 26)

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.


1. Create a module

To create a module just save the code you want in a file with the file extension .py.

For example, save this code in a file named mymodule.py:

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

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

2. Import module (import, from, as)

Now we can use the module we just created, by using the import statement.

import mymodule

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

Re-naming a Module (as)

You can create an alias when you import a module, by using the as keyword.

import mymodule as mx

a = mx.person1["age"]

Import From Module (from)

You can choose to import only parts from a module, by using the from keyword. When importing using the from keyword, do not use the module name when referring to elements in the module.

from mymodule import person1

print(person1["age"])

3. Built-in modules

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

import platform

x = platform.system()
print(x) # e.g., 'Windows' or 'Linux'

Using the dir() function, you can list all the function names (or variable names) in a module.

import platform
x = dir(platform)
print(x)

4. Module search path

When you import a module, the Python interpreter searches for the module in the following sequences:

  1. The current directory.
  2. If not found, Python searches each directory in the shell variable PYTHONPATH.
  3. If all else fails, Python checks the default path (e.g., /usr/local/lib/python).

You can check the path by importing the sys module:

import sys
print(sys.path)

5. __name__ == "__main__"

When the Python interpreter reads a source file, it executes all of the code found in it. Before executing the code, it will define a few special variables. One of them is __name__.

  • If you execute the module as a script (e.g., python mymodule.py), __name__ is set to "__main__".
  • If you import the module from another script, __name__ is set to the module’s name.

This allows us to write code that only runs when the script is executed directly:

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

# This block only runs if you run this file directly.
# It does NOT run if someone imports this module.
if __name__ == "__main__":
    print("Running as main program")
    greeting("Admin")

Discussion

Loading comments...