This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Importing Modules

I hope the previous lesson has helped you really understand what you are doing when you import a module.

Now, let us try to write a module of our own, and then import and use the functions and classes from that module.

So now, copy the script below into a text editor and name it my_module.py. Note that I am naming FACTOR in uppercase to indicate that I want this to act like a constant.

FACTOR = 5

class Monster:
    def __init__(self, name="Me", food="cookies"):
        self.name = name
        self.food = food

    def talk(self):
        print(f"{self.name} love {self.food}!")


def spawn_monsters():
    return [Monster("Happy", "carrots"), 
            Monster("Bashful", "ice-creams"), 
            Monster("Wild", "cookies")]

def calculate_growthrate(adjustment=3):
    return 25 * FACTOR + adjustment

If you try running this script, nothing will happen (obviously).

Now, let’s write another script (call it my_script.py) to import our module.

import my_module

print(dir())

print(my_module.FACTOR)

print(my_module.calculate_growthrate(2))

monsters = my_module.spawn_monsters()

new_monster = my_module.Monster("Crazy", "sashimi")
monsters.append(new_monster)

for monster in monsters:
    monster.talk()

Run your script, and it should work!

You may also import multiple modules in a single line.

import my_module, os

Now if you are finding it tedious to type my_module every time you want to use a function or a class from the module, you can assign it a different name instead (for example mm). This is also useful to resolve any conflict with existing names (maybe you already have a different variable named my_module?).

import my_module as mm

print(dir())
print(mm.FACTOR)
print(mm.calculate_growthrate(2))
monsters = mm.spawn_monsters()
new_monster = mm.Monster("Crazy", "sashimi")

Note that you now have mm in your namespace.

If you are even lazier (especially when you may refer to my_module a lot in the script, you can just import the functions and classes directly instead).

from my_module import calculate_growthrate
print(calculate_growthrate(2))

You can import multiple variables/functions/classes in a single line too.

from my_module import FACTOR, calculate_growthrate, spawn_monsters, Monster
print(FACTOR)
print(calculate_growthrate(2))
monsters = spawn_monsters()
new_monster = Monster("Crazy", "sashimi")

You can also rename your variables, functions and classes. If you check your namespace, you will find that it contains growth and Mon.

from my_module import calculate_growthrate as growth, Monster as Mon
print(dir())
print(growth(2))
new_monster = Mon("Crazy", "sashimi")

If you are super duper lazy, you can just import everything from the module.

from my_module import *

This will import all objects from my_module except those that start with an underscore.

But avoid doing this (unless you have a very clear reason to, and laziness is not one of them!). This will make your code very difficult to read (“where did this calculate_growthrate() function come from?”), and you may end up unintentionally replacing some variables in your script with something from the module with the same name. Import only the functions or classes that you need!

Bonus

Let’s say you have imported your module on an interactive Python interpreter. Then you made changes to my_module.py. You can test the new version without existing the Python interpreter and starting it again, by reloading the module usingthe function reload() from importlib.

import my_module
import importlib 
importlib.reload(mymodule)