Defining and calling functions is where a simple script turns into software that you can reuse. A def statement creates a function object and binds it to a name, and the parentheses that you add at the call site are what actually run the body of the function. This lesson explains what happens at each of those moments, how to pass arguments in the ways that Python supports, and why functions are ordinary values that you can store, pass around, and look up in a dictionary.
This is the first lesson in the Python Functions module, and the next lesson in this module is about "Positional, Keyword and Default Arguments".
What does def actually do?
When Python reaches a def line, it does three things. It compiles the body into a code object, it builds a function object that holds that code, and it binds the name that you wrote to that object. The body itself does not run. That is the whole difference between defining a function and calling one, and it explains why a function can sit in your file for a long time without producing any output at all.
Because the binding is only a name, you can rebind it. Running the same def statement a second time replaces the name with a brand new function object, and any reference that you captured earlier still points at the old one.
def greet(name):
"""Return a greeting for name."""
return 'Hello, ' + name + '!'
print(greet('Ada'))
print(greet('Grace'))
# The name now points at a different function object.
def greet(name):
"""A newer, louder greeting."""
return 'HEY ' + name.upper() + '!'
print(greet('Ada'))
print(greet.__doc__)
That is also why a def inside a loop, or inside another function, is a common source of confusion. The name is created fresh each time the statement executes, and the last one wins.
The function object carries a small amount of information about where it came from. greet.__module__ tells you the module that it was defined in, and greet.__qualname__ gives the full dotted path. That is how a traceback can point at Outer.<locals>.inner when a function is nested inside another one. None of this changes the way that you call the function, but it explains why a function printed to the console looks more like a small record than like a block of code.
def greet(name):
"""Return a greeting for name."""
return 'Hello, ' + name + '!'
print(greet.__module__)
print(greet.__qualname__)
print(callable(greet))
print(greet('Ada'))
Type hints are optional in Python, but they earn their place as soon as a function has more than one or two parameters. The annotation def greet(name: str) -> str: is ignored while the program runs, and yet it tells your editor exactly what to expect, and it lets a type checker catch a mismatch before you run anything.
Why does the body only run when you call it?
Calling a function means writing the name, then the parentheses, then the arguments. Everything inside the body then runs from top to bottom, in a fresh local scope that has its own set of variable names. When the body reaches a return, the value on the right-hand side is handed back to the caller and the function stops there.
Arguments are worked out at the moment of the call, in the scope of the caller. That detail matters more than it sounds, because it means that if you pass a variable and then change that variable before the body of the function runs, the function sees the new value. Working out the arguments and running the body are two separate steps.
def show(value):
print('function sees:', value)
number = 10
show(number)
number = 20
show(number)
Two habits separate people who write maintainable Python from people who fight with it. First, a function that returns a value is easy to test and easy to reuse, while a function that only prints forces the caller to scrape text back off the screen. Second, a function should do one job, and its name should read like a sentence: calculate_total, parse_config, send_welcome_email.
The most common beginner mistake here is a function that both prints and returns. The caller gets a value and also sees output on the terminal, and when you test the function later the printed text pollutes your test log even though the logic depends on the returned value. Pick one. A function that computes returns, and the outermost layer of your program decides what to print.
How do you call a function?
Python gives you several ways to pass arguments, and the differences show up in every real codebase.
| Call style | What it means | Example |
|---|---|---|
| Positional | Values are matched to parameters by position | greet("Ada") |
| Keyword | Values are matched by parameter name, in any order | greet(name="Ada") |
| Mixed | Positional first, and keyword after | greet("Ada", greeting="Hi") |
| Default | Parameter has a value already, so you may leave it out | greet("Ada", punctuation="?") |
| Unpacking | Values arrive from a list or a dictionary | greet(*names), greet(**options) |
Keyword arguments make call sites self-documenting. If a function takes five parameters, then send(to=addr, subject=title, body=msg) tells the next reader exactly what each value means without making them open the definition.
A function with no return statement still returns something, and that something is None. That is why result = compute() followed by print(result) prints the word None, and it is why you should check for None with is None rather than with a truth test. The next two lessons look at argument binding and return values in detail. For now, the important habit is to read a function's signature before you call it.
Can a function live in a variable or a dictionary?
Yes. Functions are objects, exactly like integers and strings. You can assign one to a variable, put it in a list or a dictionary, pass it to another function, or return it. This is the single most useful thing to understand about Python functions, because it lets you replace long if and elif chains with a simple lookup table.
def add(a, b):
return a + b
def multiply(a, b):
return a * b
operations = {'add': add, 'multiply': multiply}
for name, operation in operations.items():
print(name, '->', operation(3, 4))
That pattern shows up everywhere in production code, in a plugin registry, in a command parser, and in a framework that maps HTTP routes to handler functions. The dictionary on the right of the assignment holds functions, so operations['add'](3, 4) works in exactly the same way that add(3, 4) does.
The same property lets you pass behaviour into a function. A function that accepts another function as a parameter is the foundation of decorators, of event handlers, and of any kind of pluggable pipeline. You will meet that style again in the advanced functions module, but the core idea is simply this. Functions are values, and values can be passed around.
How do you document a function so help() works?
Put a string literal as the first statement in the body and it becomes the function's docstring, which is stored on the __doc__ attribute. It costs one line, and it shows up in help(), in your editor's hover tooltip, and in generated documentation. Describe what the function returns, and not how it works inside.
import inspect
def greet(name, greeting='Hello', punctuation='!'):
"""Return a greeting for name, with a custom opener and ending mark."""
return greeting + ', ' + name + punctuation
print(greet.__doc__)
print(inspect.signature(greet))
print(greet('Ada'))
print(greet(greeting='Hi', name='Grace', punctuation='?'))
inspect.signature is the tool to reach for when you cannot remember the parameters of a function. It prints the exact signature, defaults included, and that is a faster answer than scrolling through a file.
Quick reference
Three mistakes account for most function bugs in new code.
- Forgetting the parentheses. Writing
greetgives you the function object, and writinggreet()runs it with no arguments. The difference shows up as<function greet at 0x...>in a printout instead of your text. - Expecting a return value that never comes. A function with no
returnhands backNone, and every operation onNonefails with anAttributeErroror aTypeErrorthat points at the wrong line. - Rebinding a function name by accident. If you write
greet = something_elseinside a function, then the name is now local, and the outer one is untouched until you sayglobal.
Now try it yourself. Write a function describe_order(item, price, quantity, discount=0) that returns a formatted summary line, and then call it four ways: positionally, with keywords, mixing both, and with the discount left out. Add a docstring, and use inspect.signature to print the signature before you call it. Finally, put two different functions into a dictionary and drive them from a loop, so that you practise treating functions as values and not only as things that you call.