Skip to content

Latest commit

 

History

History
108 lines (70 loc) · 5.03 KB

File metadata and controls

108 lines (70 loc) · 5.03 KB

Modules

Every code example so far in this book has lived in one single file, or one single REPL session. That’s fine while you’re learning, but real programs grow. Once a program gets big enough, you don’t want every function and variable crammed into one giant file - you want to split things up, and reuse code you already wrote instead of retyping it into every new program.

That’s exactly the problem modules solve.

What Is a Module?

Here’s the good news: you’ve already been creating modules this whole time, without realizing it. Any Python file you write is automatically a module. If you save some code in a file named greetings.py, you now have a module named greetings, and any other Python file can borrow the things defined inside it.

Let’s make that real with two files.

def greet_user(username):
    return "Hello, " + username + "!"

greetings.py

That’s our module - just a plain .py file with one function in it, sitting in the same folder as the program we’re about to write.

Importing a Module

The first, most basic way to use another file’s code is the plain import statement.

import greetings

message = greetings.greet_user("Mike Jones")
print(message)  # -> Hello, Mike Jones!

main.py

Notice the pattern: import greetings loads up the whole greetings.py file, and then we reach into it using a dot, greetings.greet_user(…​), the same way we’ve been reaching into objects and their methods. This is a genuinely good habit to get into, because it’s always crystal clear, just by reading the code, exactly where greet_user came from - it’s right there in the name, greetings.greet_user.

Importing Just What You Need

Sometimes you don’t want to type the module name every single time, especially if you’re going to use a function over and over. That’s what from …​ import …​ is for.

from greetings import greet_user

message = greet_user("Mike Jones")
print(message)  # -> Hello, Mike Jones!

main.py

This time, we pulled greet_user directly into main.py, so we can call it plain, with no greetings. in front. Shorter to type, and often reads a little cleaner.

You can even import several names from the same module this way, separated by commas.

from greetings import greet_user, greet_admin
Note
There’s also a from greetings import * form, which grabs everything out of a module at once. It’s tempting, but most Python programmers avoid it - once you’ve done that a few times from a few different modules, it gets hard to tell, just by looking at your code, which module any given function actually came from.

Which Style Should You Use?

Neither style is "wrong" - it’s mostly a judgment call.

  • Use import module_name when you’re using a few different things from that module, or when you like being able to see exactly where a function came from at a glance.

  • Use from module_name import name when you only need one or two things from a module and you’ll be using them a lot, and typing the module name every time would get repetitive.

Just be a little careful with the second style: if you from import a function named greet_user from two different modules, the second import silently replaces the first one. import module_name never has that problem, since everything stays safely namespaced behind the module’s name.

Modules from Python’s Standard Library

Modules aren’t just for files you write yourself. Python ships with a huge collection of modules already built in, ready for you to import - this is called the standard library. You’ve likely already seen the math module mentioned in passing; it works exactly the same way as our homemade greetings module.

import math

print(math.sqrt(64))   # -> 8.0
print(math.pi)          # -> 3.141592653589793

Or, using the second style:

from math import sqrt, pi

print(sqrt(64))  # -> 8.0
print(pi)         # -> 3.141592653589793

Same functions, same values - just a different way of reaching for them.

Tip
  • Create a file named mathhelpers.py with a function double(number) that returns number * 2

  • In a second file, import mathhelpers and call mathhelpers.double(21)

  • Now rewrite that second file using from mathhelpers import double instead, and call double(21) directly

  • Notice both versions print the same answer, just written a little differently

A Word of Caution

Modules also let you import code that other people have written - there are millions of these floating around for Python, doing everything imaginable. That’s an enormous amount of free help. But it also means it’s important to know where the code you’re importing actually comes from. Not everything you find is trustworthy, and importing someone else’s module means running their code, right alongside yours. Stick to well-known, widely-used packages, especially while you’re still learning to tell the difference yourself.

See https://docs.python.org/3/tutorial/modules.html for a deeper dive into everything modules can do.