01 / 07
Modules and the standard library
INPUT · Slides
Three ways to bring one in
02 / 07
One: take the whole thing
Revision first. Say calc.py has this in it.
def add(a, b): return a + bdef subtract(a, b): return a - bimport calc takes that file whole. To call, you put calc. on the front.
import calcprint(calc.add(10, 4))That shows 14. You can see at a glance where a function came from, which is what this shape has going for it.
03 / 07
Two: take only what you need
Write from calc import add and you take the name on its own. No calc. when you call.
from calc import addprint(add(10, 4))That shows 14 as well. It is doing the same thing — only what you call it by has got shorter.
04 / 07
Shorter, but the source disappears
The from shape writes short, and gives something up in return. Where that name came from cannot be told from the line that calls it.
Worse is when your own file has a function of the same name. Whichever was written later overwrites the other. No error comes out and only the answer changes, which makes for a bug that hides well.
When in doubt, the import calc shape. Pick the one where names cannot collide and you are safe.
05 / 07
Three: give it a short name
Write import calc as c and you can call it by a short name, as c.add(10, 4). The word as reads as you would expect: bring this in under that name.
import calc as cprint(c.add(10, 4))You reach for it when a long module name would come up over and over. In real code it is usually a short name the world has settled on, as with import numpy as np. Shortening on your own initiative leaves your reader guessing, so keep to the usual ones.
06 / 07
The three side by side
Set the writing next to the calling.
| how you write it | how you call it |
|---|---|
import calc | calc.add() |
from calc import add | add() |
import calc as c | c.add() |
All three are doing the same thing. Each is calling the add in the same calc.py.
The knack for telling them apart is whether the line starts with from. If it does, it is the shape you call without a dot.
07 / 07
That is other people's imports readable
With the three of them learned, the import lines gathered at the top of somebody else's code become readable. They are the list of what that program leans on.
In the next group we bring in the tools that come with Python. There is a startling amount in there that you never have to write yourself, math and random among it.