Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. def (Function Definition)

def (Function Definition)

In Python, functions are defined with the def keyword. Arguments can have default values, and callers can specify arguments in any order using keyword arguments. Since Python 3.8, positional-only (/) and keyword-only (*) separators can be used to restrict how arguments are passed. Omitting return causes None to be returned by default.

Syntax

# Basic syntax
def func_name(arg1, arg2):
    # processing
    return return_value

# Arguments with default values
def func_name(arg1, arg2=default_value):
    return return_value

# Positional-only (/) and keyword-only (*) separators
# Left of / must be positional; right of * must be keyword
def func_name(pos_only, /, normal, *, kw_only):
    return return_value

# Variable-length positional arguments (received as a tuple)
def func_name(*args):
    return args

# Variable-length keyword arguments (received as a dict)
def func_name(**kwargs):
    return kwargs

Keyword / Syntax Reference

SyntaxNotes
def func_name(args):Defines a function. The indented block becomes the function body.
return valueReturns a value to the caller and exits the function. If omitted, None is returned.
arg=defaultSpecifies a default value used when the argument is omitted. Arguments with defaults must be grouped at the end.
func(arg_name=value)Passes an argument by name as a keyword argument at call time. Can be passed regardless of order.
def f(a, /, b, *, c):Left of / must be positional-only; right of * must be keyword-only.
*argsAccepts any number of positional arguments together as a tuple.
**kwargsAccepts any number of keyword arguments together as a dictionary.

Sample Code

Basic function definition and return. Omitting return causes None to be returned.

basic_def.py
# A function that introduces a Steins;Gate character.
def greet(name):
    return "Welcome, " + name + "! We're glad to have you as a Lab Member."

# Call the function and receive the return value.
message = greet("Makise Kurisu")
print(message)

# A function without return returns None.
def log_entry(name):
    print(name + " has entered the lab")
    # No return, so None is returned.

result = log_entry("Okabe Rintaro")
print("Return value:", result)    # None is displayed.
python3 basic_def.py
Welcome, Makise Kurisu! We're glad to have you as a Lab Member.
Okabe Rintaro has entered the lab
Return value: None

Using default-value arguments. The default value is applied when the argument is omitted.

default_args.py
# A function that displays a lab member's status.
# divergence is an argument with a default value and can be omitted.
def show_status(name, divergence=0.000000):
    print(name + " / World Line: " + str(divergence) + "%")

# Omitting divergence uses the default value 0.000000.
show_status("Okabe Rintaro")

# Passing a value overrides the default.
show_status("Okabe Rintaro", 1.048596)

# A function with multiple default arguments
def make_dmail(sender, receiver, body, is_critical=False):
    prefix = "[URGENT] " if is_critical else ""
    return prefix + sender + " -> " + receiver + ": " + body

print(make_dmail("Okarin", "Mayuri", "Steins;Gate Choice"))
print(make_dmail("Hououin Kyouma", "Part-time warrior", "Tomorrow's fate changes", True))
python3 default_args.py
Okabe Rintaro / World Line: 0.0%
Okabe Rintaro / World Line: 1.048596%
Okarin -> Mayuri: Steins;Gate Choice
[URGENT] Hououin Kyouma -> Part-time warrior: Tomorrow's fate changes

Calling with keyword arguments specifying argument names. Using names allows arguments to be passed in any order.

keyword_args.py
# A function for configuring a D-Mail send.
def send_dmail(sender, receiver, body, year, month, day):
    print("[D-Mail Send]")
    print("  From  :", sender)
    print("  To    :", receiver)
    print("  Body  :", body)
    print("  Target:", str(year) + "/" + str(month) + "/" + str(day))

# Keyword arguments: specifying names allows any order.
send_dmail(
    receiver="Past Okabe Rintaro",
    sender="Okabe Rintaro",
    body="Wait at Akihabara",
    day=28,
    month=7,
    year=2010,
)
python3 keyword_args.py
[D-Mail Send]
  From  : Okabe Rintaro
  To    : Past Okabe Rintaro
  Body  : Wait at Akihabara
  Target: 2010/7/28

Using positional-only (/) and keyword-only (*) separators.

pos_kw_only.py
# Arguments left of / must be passed positionally.
# Arguments right of * must be passed as keyword arguments.
def register_labmem(name, /, lab_id, *, codename):
    print("Lab Member registered: #" + str(lab_id) + " " + name + " (" + codename + ")")

# name is positional-only, codename is keyword-only.
register_labmem("Okabe Rintaro", 1, codename="Hououin Kyouma")
register_labmem("Makise Kurisu", 2, codename="Assistant")
register_labmem("Shiina Mayuri", 3, codename="Part-time warrior")

# The following would cause errors.
# register_labmem(name="Okabe Rintaro", lab_id=1, codename="Hououin Kyouma")
# -> name is left of /, so name= cannot be used.

# register_labmem("Hashida Itaru", 4, "Daru's Ambition")
# -> codename is right of *, so codename= must be specified.
python3 pos_kw_only.py
Lab Member registered: #1 Okabe Rintaro (Hououin Kyouma)
Lab Member registered: #2 Makise Kurisu (Assistant)
Lab Member registered: #3 Shiina Mayuri (Part-time warrior)

Functions are objects. They can be assigned to variables or passed as arguments to other functions.

first_class.py
# Functions that evaluate world line states.
def is_beta(divergence):
    return divergence >= 1.000000

def is_steins_gate(divergence):
    return abs(divergence - 1.048596) < 0.000001

# A function can be assigned to a variable (function object).
check = is_beta
print(check(1.048596))     # True

# A function can be passed as an argument to another function (higher-order function).
def evaluate_world(divergence, checker):
    if checker(divergence):
        return "World line meets the condition"
    return "Does not meet the condition"

print(evaluate_world(1.048596, is_steins_gate))
print(evaluate_world(0.571015, is_steins_gate))

# Functions can be stored in a list and called in sequence.
checkers = [is_beta, is_steins_gate]
divergence = 1.048596
for fn in checkers:
    print(fn.__name__ + ":", fn(divergence))
python3 first_class.py
True
World line meets the condition
Does not meet the condition
is_beta: True
is_steins_gate: True

Common Mistakes

Common Mistake 1: The mutable default value trap

When a mutable object such as a list or dict is used as a default value, that object is created only once at function definition time and shared across all calls. A new list is not created on each call.

ng_mutable_default.py
# NG: the default list is shared across all calls.
def add_member(name, members=[]):
    members.append(name)
    return members

print(add_member("Okabe Rintaro"))
print(add_member("Makise Kurisu"))   # Previous call's result remains.
print(add_member("Shiina Mayuri"))   # It keeps accumulating.
python3 ng_mutable_default.py
['Okabe Rintaro']
['Okabe Rintaro', 'Makise Kurisu']
['Okabe Rintaro', 'Makise Kurisu', 'Shiina Mayuri']
ok_mutable_default.py
# OK: use None as the default value and initialize inside the function.
def add_member(name, members=None):
    if members is None:
        members = []
    members.append(name)
    return members

print(add_member("Okabe Rintaro"))
print(add_member("Makise Kurisu"))   # A new list is created each time.
print(add_member("Shiina Mayuri"))
python3 ok_mutable_default.py
['Okabe Rintaro']
['Makise Kurisu']
['Shiina Mayuri']

Common Mistake 2: Non-default argument following default argument causes SyntaxError

Arguments without default values must be written before arguments with default values. Writing them after causes a SyntaxError.

ng_arg_order.py
# NG: argument without default is written after argument with default.
def send_dmail(sender, body="(no body)", receiver):
    print(sender, "->", receiver, ":", body)
python3 ng_arg_order.py
  File "ng_arg_order.py", line 2
    def send_dmail(sender, body="(no body)", receiver):
                                             ^^^^^^^^
SyntaxError: non-default argument follows default argument
ok_arg_order.py
# OK: write arguments without default values first.
def send_dmail(sender, receiver, body="(no body)"):
    print(sender, "->", receiver, ":", body)

send_dmail("Okabe Rintaro", "Past Okabe Rintaro")
send_dmail("Hououin Kyouma", "Mayuri", "Steins;Gate Choice")
python3 ok_arg_order.py
Okabe Rintaro -> Past Okabe Rintaro : (no body)
Hououin Kyouma -> Mayuri : Steins;Gate Choice

Common Mistake 3: Calling a function before it is defined causes NameError

Python's def statement is evaluated at runtime. Calling a function before it is defined causes a NameError.

ng_call_before_def.py
# NG: calling the function before it is defined.
greet("Makise Kurisu")

def greet(name):
    print("Welcome, " + name + "! We're glad to have you as a Lab Member.")
python3 ng_call_before_def.py
Traceback (most recent call last):
  File "ng_call_before_def.py", line 2, in <module>
    greet("Makise Kurisu")
    ^^^^^
NameError: name 'greet' is not defined
ok_call_before_def.py
# OK: define the function before calling it.
def greet(name):
    print("Welcome, " + name + "! We're glad to have you as a Lab Member.")

greet("Makise Kurisu")
greet("Okabe Rintaro")
python3 ok_call_before_def.py
Welcome, Makise Kurisu! We're glad to have you as a Lab Member.
Welcome, Okabe Rintaro! We're glad to have you as a Lab Member.

Notes

Python's def statement is a statement evaluated at runtime. When a function definition is executed, a function object is created and assigned to a variable with the function's name. This is why functions can be assigned to variables and passed as arguments to other functions (first-class objects).

Default values are evaluated only once at function definition time. Using a mutable object (list, dict, etc.) as a default value creates a trap where the value is shared across calls. The standard pattern for mutable defaults is to use None as the default and initialize inside the function.

Positional-only (/) and keyword-only (*) arguments are available since Python 3.8. They are useful when designing library APIs to convey intent such as "changing argument names won't affect callers" or "important settings must be explicitly specified as keyword arguments". Also see lambda for anonymous functions, and decorators for functions that wrap other functions.

If you find any errors or copyright issues, please .