Back to Explore
GuideVibeFix editorialUpdated Nov 21, 2026

Pack repeated work into functions and split files into modules: Python functions and modules

A function packs repeated work into a name; a module packs definitions into a file you take out with import. Following Chapter 4 sections 4.8-4.9 and Chapter 6 of the official Python Tutorial: def and return, local and global scope, defaults evaluated once, keyword arguments, *args and **kwargs, / and *, lambda, docstrings and annotations, the ways to import, the __main__ guard, packages and the search path — plus a 100-accident breakdown from a fictional bookstore script.

Real photo: hands typing on a laptop showing Python code with def statements on screen, a blue notebook and eyeglasses beside it

First, the boundaries of this guide. This is the second guide in the "Python Basics" series, continuing from the first: the first covered storing numbers, text, and lists, and using if, for, and while to let a program decide things and repeat work. This one covers packing repeated work away and splitting files apart. The split is this: the first guide only taught "writing one piece of code that runs"; this one teaches "packing code into functions and splitting functions into modules". How functions are written, how arguments are passed, how names are found, and how files are split are all covered here. Classes are not in this guide; they are the starting point of the next series. The example is still the fictional "Morning Light Bookstore": a small neighborhood bookstore's bookkeeping script, which by the end of the first guide could work out the total stock value and give 10% off books over 50. This time it is packed into functions you can reuse and modules that can import each other. Every operation, code sample, and number built around it was made up to explain how things work; none of it is a real record. Every statement about functions comes from two chapters of the official Python Tutorial: "More Control Flow Tools" (Chapter 4, sections 4.8–4.9) and "Modules" (Chapter 6). Sources are listed in each guide's meta information and evidence record. By the end of this guide you should be able to do four things: write functions with parameters and return values; know the rules for default arguments, keyword arguments, *args, and **kwargs; know how names are looked up inside a function; and split code into modules, using the __main__ guard so one file can be both imported and run as a script.

Step 1: def and return: pack repeated work into a name

At the end of the first guide, the bookstore's discount rule lived inside a loop: prices over 50 were multiplied by 0.9. Checkout needs the same rule, and stock-taking needs it too; copy the same code three times and you have to change it in three places when the rule changes. A function packs that code into a name: when you want a discount, you call the name and hand it the price. Write def, the function name, the parameters in parentheses, and a colon, then indent the body four spaces on the next line. The docs' example packs the Fibonacci series into a function:

>>> def fib(n):    # write Fibonacci series less than n
...     """Print a Fibonacci series less than n."""
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

The string on the first line of the body is a "docstring": a note for people, saying what the function does. The docs advise making a habit of writing them, because tools can use docstrings to produce documentation automatically. When you call the function, you write its name and parentheses; what goes in the parentheses is an "argument" — the real value handed in — while the names in the definition are "parameters" — the names that receive the values. The function name is itself a name that can be handed to another variable: after f = fib, f(100) and fib(100) are the same thing.

fib only prints; it hands nothing back. To hand a worked-out result back, use return:

>>> def fib2(n):  # return Fibonacci series up to n
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)
...         a, b = b, a+b
...     return result
...
>>> f100 = fib2(100)
>>> f100
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Here is a point that often confuses beginners: even functions without a return statement do return a value — a rather boring one, called None, meaning "nothing at all". The interpreter normally does not print None, but you can see it if you really want to:

>>> fib(0)
>>> print(fib(0))
None

fib(0) first prints a blank line (the print() at the end of the function body), and then print(fib(0)) prints None. So "the function returns nothing" is not quite accurate; the accurate way to say it is "the function returns None". The bookstore's discount function should use return to hand the discounted price back, not just print it:

>>> def price_after_discount(price, rate=0.9):
...     """10% off when the price is 50 or more, otherwise the original price."""
...     if price >= 50:
...         return round(price * rate, 2)
...     return price
...
>>> price_after_discount(59.0)
53.1
>>> price_after_discount(39.5)
39.5

59.0 is 50 or more, so 10% off gives 53.1; 39.5 is under 50, so it comes back unchanged. Note that a function can have two return statements: when the first condition holds, it returns from there and the rest never runs. My judgment is: before writing a function, decide two things — what it takes in, and what it hands back. What it takes in goes in the parentheses; what it hands back goes in a return. A function that only prints and hands nothing back cannot have its result used by anyone else, and sooner or later it has to be rewritten.

Step 2: Local and global: how names are found inside a function

When a function runs, it opens a new "local symbol table" just for that function's own variables. When a name is looked up, Python searches in a fixed order: first the local symbol table, then the local symbol tables of enclosing functions, then the global symbol table, and finally the table of built-in names. The docs put it this way: all variable assignments in a function store the value in the local symbol table; global variables can be read directly, but to assign a value to one inside a function you must name it in a global statement first.

Reading first: a name defined outside a function can be read inside it directly:

>>> STORE_NAME = 'Morning Light Bookstore'
>>> def read_store():
...     return STORE_NAME
...
>>> read_store()
'Morning Light Bookstore'

Writing is different: writing GLOBAL_COUNTER = 1 inside a function changes a fresh local variable of the function, and the one outside does not move at all:

>>> GLOBAL_COUNTER = 0
>>> def bump_wrong():
...     GLOBAL_COUNTER = 1  # this is local; the outside never sees it
...     return GLOBAL_COUNTER
...
>>> bump_wrong()
1
>>> GLOBAL_COUNTER
0

To really change the outside one, declare it first with a global statement inside the function:

>>> GLOBAL_COUNTER2 = 0
>>> def bump_right():
...     global GLOBAL_COUNTER2
...     GLOBAL_COUNTER2 += 1
...     return GLOBAL_COUNTER2
...
>>> bump_right()
1
>>> GLOBAL_COUNTER2
1

There is a sneakier mistake: read a name inside a function and then assign to it later, and Python treats that name as local from the start, so the read raises an UnboundLocalError — a local variable referenced before assignment. To change a variable of an enclosing function from a nested function, name it in a nonlocal statement:

>>> def make_counter():
...     n = 0
...     def inc():
...         nonlocal n
...         n += 1
...         return n
...     return inc
...
>>> c = make_counter()
>>> c()
1
>>> c()
2

Every time a function is called — even when it calls itself — a new local symbol table is created for that call, so recursion never tangles the variables of different levels together. Arguments are passed "by value", where the value is always an object reference rather than a copy of the object: pass a list into a function and change it there, and the list outside changes too — the same rule as "assignment never copies" from the first guide. My judgment is: avoid changing global variables when you can. Let a function take what it needs from its parameters and hand its result back with return; such a function runs anywhere you put it. A function that reads and writes globals from the start has to be changed every time it moves house.

Step 3: Default arguments: fewer arguments still run, but the default is worked out only once

Some parameters are the same value most of the time, and passing them every time is tedious. You can give them a default value: call the function without one and the default is used; pass one and the passed value wins. The docs' example is a function that asks "is this OK?":

>>> def ask_ok(prompt, retries=4, reminder='Please try again!'):
...     while True:
...         reply = input(prompt)
...         if reply in {'y', 'ye', 'yes'}:
...             return True
...         if reply in {'n', 'no', 'nop', 'nope'}:
...             return False
...         retries = retries - 1
...         if retries < 0:
...             raise ValueError('invalid user response')
...         print(reminder)
...
>>> ask_ok('Do you really want to quit?')  # only the mandatory argument
>>> ask_ok('OK to overwrite the file?', 2)  # one of the optional arguments
>>> ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')  # all arguments

The example also introduces the in keyword: reply in {'y', 'ye', 'yes'} asks whether the user's reply is one of those three. All three calls are valid: only the mandatory argument, one optional argument, or all of them.

There is one key rule about defaults: they are evaluated at the point of function definition, in the defining scope — not each time the function is called. The docs' example:

>>> i = 5
>>> def f(arg=i):
...     print(arg)
...
>>> i = 6
>>> f()
5

i later became 6, but the function still prints 5, because the default was fixed when the function was defined. That rule is easy to miss until the default is something that can be changed — a list or a dictionary — and then it matters a lot. The docs give an explicit warning about it:

>>> def f(a, L=[]):
...     L.append(a)
...     return L
...
>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]

Three calls, and the list keeps growing: the default [] was evaluated only once, when the function was defined, so all three calls share the same list. To get a fresh list on every call, write the default as None and build the list inside the function:

>>> def f(a, L=None):
...     if L is None:
...         L = []
...     L.append(a)
...     return L
...
>>> f(1)
[1]
>>> f(2)
[2]

The bookstore's discount function price_after_discount(price, rate=0.9) does not have this problem: 0.9 is a number, it cannot be changed, and evaluating it once at definition time gives the same result as evaluating it on every call. My judgment is: only write defaults that cannot be changed — numbers, strings, None. For anything mutable, like a list or a dictionary, write None and build it fresh inside the function. This is one of the most famous traps in Python, and it is the second category of accident in the chart below.

Step 4: Keyword arguments: pass them by name

Positional arguments are matched in order: the first argument goes to the first parameter, the second to the second. When there are many parameters, the order is easy to mix up. Keyword arguments are passed "by name": write the parameter's name, an equals sign, and the value, and the order no longer matters. The docs' example is a parrot:

>>> def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.")
...     print("-- Lovely plumage, the", type)
...     print("-- It's", state, "!")
...
>>> parrot(1000)                                          # 1 positional argument
>>> parrot(voltage=1000)                                  # 1 keyword argument
>>> parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
>>> parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments, order reversed, still fine
>>> parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
>>> parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

All six calls are valid. But the four below are not, and the docs list them one by one:

>>> parrot()                     # required argument missing
>>> parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
>>> parrot(110, voltage=220)     # duplicate value for the same argument
>>> parrot(actor='John Cleese')  # unknown keyword argument

Three rules cover it: in a function call, keyword arguments must follow positional arguments; no argument may receive a value more than once; and every keyword argument passed must match one of the arguments the function accepts. The "duplicate value" rule has a variant that is easy to trip over:

>>> def function(a):
...     pass
...
>>> function(0, a=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for argument 'a'

In function(0, a=0), a gets 0 by position and then 0 again by keyword — one argument given twice, so it raises a TypeError. The second invalid call has a subtle detail: parrot(voltage=5.0, 'dead') never even reaches the running stage; a positional argument after a keyword argument is a SyntaxError, and the interpreter rejects it while reading the code.

The bookstore version: at checkout, member and non-member prices are told apart by a keyword:

>>> def checkout(*prices, member=False):
...     total = sum(prices)
...     if member:
...         total = round(total * 0.95, 2)
...     return total
...
>>> checkout(39.5, 59.0)
98.5
>>> checkout(40.0, 60.0, member=True)
95.0

member=True sits at the end, and anyone reading the call can see at a glance that this is a member checkout. One more thing about floats: checkout(39.5, 59.0, member=True) looks like 98.5 times 0.95, which is 93.575 on paper — but in floating-point arithmetic, 39.5 plus 59.0 times 0.95 is actually stored as 93.57499999999999, and rounding to two decimals gives 93.57, not 93.58. The same digits, reached by a different path, can be a cent apart. Remember that when money is involved: count in integer cents, or use the decimal module, and do not trust the tail of a float.

Step 5: *args and **kwargs: take as many arguments as come

Sometimes you do not know when writing the code how many arguments a function will get: checkout might be one book, or ten. Starred parameters handle that: one star, *args, collects the extra positional arguments into a tuple; two stars, **kwargs, collects the extra keyword arguments into a dictionary. The docs' cheese-shop example:

>>> def cheeseshop(kind, *arguments, **keywords):
...     print("-- Do you have any", kind, "?")
...     print("-- I'm sorry, we're all out of", kind)
...     for arg in arguments:
...         print(arg)
...     print("-" * 40)
...     for kw in keywords:
...         print(kw, ":", keywords[kw])
...
>>> cheeseshop("Limburger", "It's very runny, sir.",
...            "It's really very, VERY runny, sir.",
...            shopkeeper="Michael Palin",
...            client="John Cleese",
...            sketch="Cheese Shop Sketch")
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

Note that the first line prints Limburger ? with a space before the question mark: print() puts a space between its arguments. The order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call — the docs say so explicitly.

The most common partner for *args is a parameter like sep that can only be passed by keyword: it sits after *args, so it cannot be passed by position at all:

>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'

Stars work in reverse too: at the call site, unpack a list into separate positional arguments with *, and unpack a dictionary into keyword arguments with **:

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

The bookstore's checkout(*prices, member=False) follows the same pattern: *prices takes the prices of however many books there are, and member can only be passed by keyword, so checkout(39.5, 59.0, member=True) can never mistake True for the price of a third book. My judgment is: once a function has more than three parameters, or one of them is a switch, make the switch a keyword parameter; when the count is not fixed, use *args. Then callers do not have to count positions, and readers can see what is going on at a glance.

Step 6: / and *: fix how arguments may be passed, too

By default, arguments may be passed to a function either by position or explicitly by keyword. But some functions want to fix that as well: some parameters only by position, others only by keyword. Two symbols control it: / and *. Parameters before / are positional-only; parameters after * are keyword-only; parameters in the middle can go either way:

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
      -----------    ----------     ----------
        |             |                  |
        |        Positional or keyword   |
        |                                - Keyword only
         -- Positional only

The block above is a diagram from the official docs, not code you can run: / on the left means positional-only, * on the right means keyword-only, and the middle takes both. The four functions below are the ones that actually run:

>>> def standard_arg(arg):
...     print(arg)
...
>>> def pos_only_arg(arg, /):
...     print(arg)
...
>>> def kwd_only_arg(*, arg):
...     print(arg)
...
>>> def combined_example(pos_only, /, standard, *, kwd_only):
...     print(pos_only, standard, kwd_only)
...
>>> standard_arg(2)
2
>>> standard_arg(arg=2)
2
>>> pos_only_arg(1)
1
>>> pos_only_arg(arg=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg'
>>> kwd_only_arg(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given
>>> kwd_only_arg(arg=3)
3
>>> combined_example(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: combined_example() takes 2 positional arguments but 3 were given
>>> combined_example(1, 2, kwd_only=3)
1 2 3
>>> combined_example(1, standard=2, kwd_only=3)
1 2 3

The docs' guidance on when to use each: use positional-only if you want the name of the parameter to not be available to the user — useful when parameter names have no real meaning, or when you want to enforce the order of the arguments; use keyword-only when names have meaning and the function definition is more understandable by being explicit with names, or when you want to prevent users from relying on the position of the argument; and for an API, use positional-only to prevent breaking API changes if the parameter's name is modified in the future.

Positional-only parameters have one more neat use: they can untangle a collision with **kwargs. Look at this function:

>>> def foo(name, **kwds):
...     return 'name' in kwds
...
>>> foo(1, **{'name': 2})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'name'

The key 'name' can never reach kwds, because the parameter name grabs it first. But put a / after name so it can only be passed by position, and the keyword 'name' flows into kwds without a problem:

>>> def foo(name, /, **kwds):
...     return 'name' in kwds
...
>>> foo(1, **{'name': 2})
True

This step is on the advanced side; at the start you do not need it every day, and recognizing the two symbols when you read other people's code is enough. My judgment is: for small scripts of your own, plain parameters are fine; for a utility function other people will use, consider using / and * to lock down how it is called.

Step 7: lambda: a small function in one line

Sometimes the function you need is so small it is only one line: "sort by the second character of the title", or "add 10 to the price". Writing a full def for that feels long-winded. lambda is the shorthand for such small functions: lambda parameters: expression, where the part after the colon can only be a single expression, and the value it works out is the return value. The docs' example:

>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

make_incrementor(42) hands back a small function that still remembers n is 42, so f(0) is 42 and f(1) is 43. Another common use is as the "key" for sorting:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

key=lambda pair: pair[1] means: when sorting, do not compare the first element; compare the second element of each tuple. A lambda is, semantically, just syntactic sugar for a normal function definition — only it is restricted to a single expression. My judgment is: use lambda only where it fits on one line and can be read at a glance, such as a sort key or a quick conversion; anything longer than a line deserves a proper def, where you can also write a docstring.

Step 8: Docstrings and annotations: leave the function a name card

Step 1 introduced docstrings. The docs set out conventions for them: the first line should always be a short, concise summary of the object's purpose, beginning with a capital letter and ending with a period; if there are more lines, the second line should be blank, visually separating the summary from the rest. Tools use docstrings to automatically produce documentation, so writing them is the same as writing the manual as you go:

>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything:
...
...         >>> my_function()
...         >>>
...     """
...     pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.

No, really, it doesn't do anything:
    >>> my_function()
    >>>

A docstring lives in the function's __doc__ attribute and can be read at any time. Another "name card" is annotations: a colon after a parameter name, and a literal -> between the parameter list and the colon for the return value. They are completely optional metadata about the types used by the function, stored in the function's __annotations__ attribute as a dictionary. The key point is that they have no effect on any other part of the function:

>>> def f(ham: str, eggs: str = 'eggs') -> str:
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...     return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'

The annotation says ham should be a str, but if you actually pass an integer, Python will not stop you — f(123) fails at ham + ' and ' + eggs with a TypeError, because an integer and a string cannot be added, not because the annotation was wrong. To catch wrong types from annotations you need a separate type-checking tool. My judgment is: annotations are written for the people reading the code, not for the interpreter; do not expect them to block mistakes, and do not skip testing just because the annotations are in place.

Step 9: Modules: put definitions in a file, take them out with import

By now the bookstore has several functions: discounts, checkout, stock totals. Squeezed into one file they are fine, but as the program gets longer it needs to be split. A module is a file containing Python definitions and statements: the file name, minus the .py, is the module name. The docs' example packs the Fibonacci functions into fibo.py:

# Fibonacci numbers module

def fib(n):
    """Write Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n):
    """Return Fibonacci series up to n."""
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

Then import it in the interpreter:

>>> import fibo
>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'

import fibo does not add fib and fib2 directly to the current namespace; it only adds the module name fibo, and you reach the functions as fibo.fib — module name, dot, name. Each module has its own private namespace, which is used as the global namespace by all functions defined in the module, so a module author can use global variables without worrying about clashing with yours. If you use a function often, assign it to a local name: after fib = fibo.fib, fib(500) works.

There are other ways to import, each with its own job:

>>> from fibo import fib, fib2  # take the names straight in, no module name needed
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
>>> import fibo as fib  # import under a different name
>>> fib.fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
>>> from fibo import fib as fibonacci  # take it in and rename it
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

There is also from fibo import *, which imports all names except those beginning with an underscore. The docs are clear about it: in most cases Python programmers do not use this, since it introduces an unknown set of names into the interpreter, possibly hiding things you have already defined. It is fine to use it to save typing in interactive sessions, but in general the practice of importing * from a module is frowned upon, since it often causes poorly readable code. Each module is only imported once per interpreter session: import the same module a second time and you get the result of the first import. If you change a module and want to test it interactively, restart the interpreter — or use importlib.reload().

When a module is first imported, Python caches the compiled version in the __pycache__ directory, which makes the next load faster. To find out which names a module defines, use dir():

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']

One honest correction is needed here: the line above is the result printed on the docs page, but on the local Python 3.12.3 used to verify this guide, dir(fibo) returns considerably more names, including __doc__, __package__, __loader__, __spec__, __file__, __cached__, and __builtins__. The docs page is written for Python 3.15.2; the three names in the list are present in both versions, and the extra ones are added by the interpreter itself — they do not change how fib and fib2 are used. The discrepancy is recorded in the evidence file.

Step 10: The __main__ guard, packages, and the search path: let a file be both imported and run as a script

A module faces a dilemma: you want other people to import fibo.py and use it, but you also want to run it yourself to check it works. Run directly, the code in the module executes from the top; imported, you do not want that test code to run as well. The answer is the global variable __name__: when a file is run as a script, __name__ is "__main__"; when it is imported, __name__ is the module's own name. Add a guard at the end of the file:

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

Run directly and you get output; import it and you hear nothing:

$ python fibo.py 50
0 1 1 2 3 5 8 13 21 34
>>> import fibo
>>> # nothing printed: the guard stopped the test code

sys.argv[1] is the first argument after the file name on the command line — here 50 — and int() turns it into an integer before passing it to fib.

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it searches for a file named spam.py in the directories listed in sys.path. sys.path is initialized from three places: the directory containing the input script (or the current directory when no file is specified), the PYTHONPATH environment variable, and the installation-dependent default (by convention including a site-packages directory). One trap to remember: the directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path, so a file of your own with the same name as a standard-library module — random.py, say — will be loaded instead of the library's. That is an error unless the replacement is intended, so do not name your files after standard-library modules.

When files multiply further, they are grouped into "packages": a way of structuring Python's module namespace by using dotted module names. The docs' example is a package for handling sound files and sound data:

sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py

The __init__.py files are required to make Python treat the directories containing them as packages. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, which tells from sound.effects import * which submodule names to import. There are three ways to import a module from a package; they mean the same thing and differ only in how much typing they save:

>>> import sound.effects.echo
>>> sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
>>> from sound.effects import echo
>>> echo.echofilter(input, output, delay=0.7, atten=4)
>>> from sound.effects.echo import echofilter
>>> echofilter(input, output, delay=0.7, atten=4)

When packages are structured into subpackages, you can use absolute imports to refer to submodules of sibling packages — or relative imports, with leading dots to indicate the current and parent packages: from . import echo is the echo in the current package, from .. import formats is formats in the parent package. But note that relative imports are based on the name of the current module's package, and since the main module does not have a package, modules intended for use as the main module of a Python application must always use absolute imports.

The chart below breaks down 100 function and module accidents from the fictional Morning Light Bookstore script in its second month of learning Python, by cause. The numbers are made up to show the distribution, but every category is a real trap covered in the ten steps above:

Bar chart: breakdown of 100 function and module mistakes in the second month of learning Python — forgot return and got None 24, mutable default argument 18, changed a global without declaring global 16, module name shadowed the standard library 12, *args in the wrong place 11, no __main__ guard 10, from module import * name clashes 9

The top spot is still the same old problem: a function that computes but never reports back. Forget return, and the caller gets None — and everything calculated from it goes wrong too. The second category is the mutable-object default argument; the third is changing a global inside a function without declaring it. Together the two add up to 34, and both come down to not thinking clearly about where names live and where things live. The fourth is a module named the same as a standard-library module — call your file random.py or math.py and the standard library gets covered up by your own file. The fifth is *args in the wrong place, so the parameters after it can never be reached. The sixth is a missing __main__ guard, so importing the file runs the whole script once. The seventh is from module import *, and the names it drags in collide.

By now the bookstore's bookkeeping script has grown from "one piece of code that runs" into "several functions that can be reused, and several modules that can import each other": the discount rule lives in pricing.py, checkout lives in checkout.py, and the main program only has to put them together. Everything from the first guide is still there — just living in a tidier house. Next up should be classes: a "book" in the bookstore is not just a few key-value pairs in a dictionary; it could be an object that works out its own price and reports its own stock. But that is where the next series begins, and this guide stops here.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles

Real photo: a developer pointing at code on a laptop screen, with two more monitors showing code behind it
Guide
When the program crashes, catch the error first: Python exception handling

An exception is not a broken program: it is Python telling you what went wrong, with a name you can catch. Following Chapter 8 of the official Python Tutorial: syntax errors vs exceptions, try/except, matching by inheritance, which errors to catch and which to leave alone, raise, else, finally, with, user-defined exceptions, chaining, and ExceptionGroup — plus a 100-accident breakdown from a fictional bookstore script.

Project BuildingPythonLearning & Career
Real photo: the aisle of an independent bookstore, wooden shelves packed with colorful book spines under warm light
Guide
Turn a book into an object and its rules into a class: Python classes and objects

A class bundles data and its rules together: one Book class gives every book its own state, methods let objects do the work themselves, and inheritance lets an e-book stand on a paper book's shoulders. Following Chapter 9 of the official Python Tutorial: class and __init__, self, methods, class vs instance variables, attribute lookup, inheritance and overriding, super(), the underscore-private convention, dataclasses, __iter__ and __next__ — plus a 100-accident chart.

Project BuildingPythonLearning & Career
Real photo: the interior of an independent bookstore, wooden shelves packed with books, a leather armchair, stacks of books on a table under warm pendant lights
Guide
Put things in boxes first, then let the program decide: Python variables, data types, and control flow

Variables are boxes for things, lists and dicts are boxes for lots of things, and if, for, and while let a program decide and repeat work on its own. Following Chapters 3-5 of the official Python Tutorial: division and the float quirk, string indexing and slicing, list assignment that never copies, dict get vs KeyError, truthiness, if/elif/else, for and range, while with break/continue/loop-else — plus a 100-accident breakdown from a fictional bookstore script.

Project BuildingPythonLearning & Career