Sideway from Sideway
Draft for Information Only


Python User-Defined Function
 Function Definitions
  Features of Function Definition
 Source and Reference

Python User-Defined Function

A user-defined function object is a block of compound statements defined by a Python function definiton.

Function Definitions

A function definition is defined as funcdef::=[decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite decorators::=decorator+ decorator::="@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE dotted_name::=identifier ("." identifier)* parameter_list::=defparameter ("," defparameter)* "," "/" ["," [parameter_list_no_posonly]] | parameter_list_no_posonly parameter_list​_no_posonly::=defparameter ("," defparameter)* ["," [parameter_list_starargs]] | parameter_list_starargs parameter_list​_starargs::="*" [parameter] ("," defparameter)* ["," ["**" parameter [","]]] | "**" parameter [","] parameter::=identifier [":" expression] defparameter::=parameter ["=" expression] funcname::=identifier ::= ::= ::=

Features of Function Definition

A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.

The function definition does not execute the function body; this gets executed only when the function is called. 2

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code

def func(): pass

is roughly equivalent to

def func(): pass
func = f1(arg)(f2(func))

except that the original function is not temporarily bound to the name func.

When one or more parameters have the form parameter = expression, the function is said to have “default parameter values.” For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter’s default value is substituted. If a parameter has a default value, all following parameters up until the “*” must also have a default value — this is a syntactic restriction that is not expressed by the grammar.

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin

Function call semantics are described in more detail in section Calls. A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form “*identifier” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “**identifier” is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type. Parameters after “*” or “*identifier” are keyword-only parameters and may only be passed used keyword arguments.

Parameters may have an annotation of the form “: expression” following the parameter name. Any parameter may have an annotation, even those of the form *identifier or **identifier. Functions may have “return” annotation of the form “-> expression” after the parameter list. These annotations can be any valid Python expression. The presence of annotations does not change the semantics of a function. The annotation values are available as values of a dictionary keyed by the parameters’ names in the __annotations__ attribute of the function object. If the annotations import from __future__ is used, annotations are preserved as strings at runtime which enables postponed evaluation. Otherwise, they are evaluated when the function definition is executed. In this case annotations may be evaluated in a different order than they appear in the source code.

It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda expressions, described in section Lambdas. Note that the lambda expression is merely a shorthand for a simplified function definition; a function defined in a “def” statement can be passed around or assigned to another name just like a function defined by a lambda expression. The “def” form is actually more powerful since it allows the execution of multiple statements and annotations.

Programmer’s note: Functions are first-class objects. A “def” statement executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section Naming and binding for details.

See also

PEP 3107 - Function Annotations

    The original specification for function annotations.
PEP 484 - Type Hints

    Definition of a standard meaning for annotations: type hints.
PEP 526 - Syntax for Variable Annotations

    Ability to type hint variable declarations, including class variables and instance variables
PEP 563 - Postponed Evaluation of Annotations

    Support for forward references within annotations by preserving annotations in a string form at runtime instead of eager evaluation.

A string literal appearing as the first statement in the function body is transformed into the function’s __doc__ attribute and therefore the function’s docstring.

Source and Reference


ID: 210200003 Last Updated: 2/3/2021 Revision: 0

Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna

Home 5






Hobbies 8


Chinese 1097

English 339

Reference 79


Hardware 249


Application 213

Digitization 32

Latex 52

Manim 205

KB 1

Numeric 19


Web 289

Unicode 504


CSS 65

SVG 46


OS 429

DeskTop 7

Python 72



Formulas 8

Algebra 84

Number Theory 206

Trigonometry 31

Geometry 34

Coordinate Geometry 2

Calculus 67

Complex Analysis 21


Tables 8


Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5


Process Control 1

Acoustics 19

FiniteElement 2

Natural Sciences

Matter 1

Electric 27

Biology 1

Geography 1

Copyright © 2000-2023 Sideway . All rights reserved Disclaimers last modified on 06 September 2019