This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Is the default value assignment of a function parameter evaluated multiple times if it is Parameter=None
Type: behavior Stage: resolved
Components: Documentation Versions: Python 3.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: docs@python Nosy List: docs@python, ezio.melotti, tocretpa
Priority: normal Keywords:

Created on 2016-02-29 10:26 by tocretpa, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg261000 - (view) Author: Albert Freeman (tocretpa) Date: 2016-02-29 10:26
def f(a, L=[]):
    L.append(a)
    return L

Seems to behave differently to
def f(a, L=None):
    L = []
    L.append(a)
    return L
Which behaves the same as (as far as I noticed) to the below code in the documentation (In the tutorial under 4. More Control Flow Tools)
def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

I am using CPython 3.5.1, what is the point of "if L is None:" in the lowermost above example? And why is None treated differently to []?
msg261001 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2016-02-29 10:30
This is not a bug, see https://docs.python.org/3.6/faq/programming.html#why-are-default-values-shared-between-objects

In the first case L is evaluated once at compile time.
In the second case L is always set to a new empty list, regardless of what you pass as second argument to f.
In the third case L is set to a new empty list only if you don't pass a second argument (or if you pass None).
History
Date User Action Args
2022-04-11 14:58:28adminsetgithub: 70645
2016-02-29 10:30:45ezio.melottisetstatus: open -> closed

type: behavior

nosy: + ezio.melotti
messages: + msg261001
resolution: not a bug
stage: resolved
2016-02-29 10:26:28tocretpacreate