Modules and the standard library

INPUT · Slides

Divide the files and call across

01 / 07

Splitting alone is not enough to call it

Last lesson you cut the work into a function per role. Next, those go in separate files.

The moment you divide the files, though, something gets in the way. The name of a function written in one file cannot be seen from the other. Calling by name alone worked because you were inside the same file.

What you reach for is import. It means "bring in".

def add(a, b):    return a + bprint(add(2, 3))

Result

5

02 / 07

A .py file simply is a module

In Python, a .py file simply is a module — a bundle of parts. No special declaration, no config file. Put the file there and it is already a module.

In calc.py you write this.

def add(a, b):    return a + b

In main.py you write this.

import calcprint(calc.add(2, 3))

Run it and 5 shows. The files came apart, and they still joined up.

03 / 07

Call it joined by a dot

Once it is in, the way to call it is module.function(). For the add in calc.py, that is calc.add(2, 3).

Read the dot as "inside". It is the same shape as writing p.name for what an instance holds, back in Chapter 5.

What goes after import is the file name with the .py taken off. import calc.py is an error, so watch for that.

04 / 07

Put your imports at the top of the file

import runs wherever you put it in a program. But gathering them at the very top of the file is the Python habit.

One look at the first few lines tells you what this file leans on. As you bring more in, you line the import lines up.

import calcimport greetingprint(calc.add(2, 3))greeting.good_morning()

05 / 07

A function you brought in is an ordinary function

Once it is in, you use it exactly as you would a function written in your own file. Arguments go in, and what comes back goes straight into a sum.

import calctotal = calc.add(120, 80)print(f"total ${total}")

That shows total $200. Which file it is written in is no concern of the caller's. That is what splitting bought you.

06 / 07

What to put in a module, and what not to

A .py file is not limited to functions. Variables and classes go in as usual, and from the other side every one of them is calc.something.

The other way round, put a print in the module and it runs the moment you bring the module in. That startles people, so it is not usually done.

Put the things that get used in the module, and keep the instructions that make it go in main.py. That is the clean division.

07 / 07

Switch tabs as you write

In the exercises, main.py and one other tab sit above the editor. Tap to switch, and fill each one in.

The one that starts running when you press the run button is always main.py.

There is more than one way to bring a file in. Two more, in fact — next lesson.