Lesson 8
Making Objects the Main Star!
Chapter 4: Python modules
Importing modules
PEP 8 recommends that you always put import
statements at the top of the file, just after any module comments and docstrings. This is generally good practice, so that you can find everything in one place.
So far, we have imported modules using the import
statement.
import math
import random
import libmonster
You can also import multiple modules in a single line, although PEP 8 explicitly discourages this.
import math, random, libmonster
Now if you are finding it tedious to type libmonster
every time you want to use a function or a class from the module, you can assign it a different name instead (for example lm
). This is also useful for resolving any conflict with existing names (maybe you already have a different variable named libmonster
? See line 6 for example)
1 2 3 4 5 6 7 8 9 10 |
|
If you are even lazier (especially if you refer to lm
a lot in the script), you can just import the functions and classes from the module directly instead. There is no need to use libmonster
or lm
to refer to these functions/classes in your code this way.
from libmonster import FACTOR
from libmonster import calculate_growthrate
from libmonster import Monster
print(FACTOR)
print(calculate_growthrate(2))
new_monster = Monster("Crazy", "sashimi")
PEP 8 says it is ok to import multiple variables/functions/classes in a single line.
from libmonster import FACTOR, calculate_growthrate, spawn_monsters, Monster
print(FACTOR)
print(calculate_growthrate(2))
monsters = spawn_monsters()
new_monster = Monster("Crazy", "sashimi")
Like the module names, you can also rename your variables, functions and classes when you import them.
from libmonster import calculate_growthrate as growth, Monster as Mon
print(growth(2))
new_monster = Mon("Crazy", "sashimi")
If you are super duper lazy, you can just import everything from the module.
from libmonster import *
print(FACTOR)
print(calculate_growthrate(2))
monsters = spawn_monsters()
new_monster = Monster("Crazy", "sashimi")
This will import all objects from libmonster
except those that start with an underscore.
But avoid doing this unless you have a very clear reason (and laziness is not one of them!) Importing this way makes your code very difficult to read (“where did this calculate_growthrate()
function come from?”). You may also 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!