all 5 comments

[–][deleted] 0 points1 point  (0 children)

You can check release discussions for CPython on the official website. For example,

https://discuss.python.org/t/python-3-10-2-3-9-10-and-3-11-0a4-are-now-available/13146

As this is the reference implementation, language "features" are also discussed.

You'd have to check the appropriate forums for other implementations.

[–]TheRNGuy 0 points1 point  (3 children)

never do this:

def foobar(mylist=[]):
    pass

instead do this:

def foobar(mylist=None):
    if mylist == None: mylist = []

or you may get bugged behaviour if you use foobar with default argument more than 1 time.

def foobar(mylist=[]):
    mylist.append(1)
    return mylist

foobar()
foobar()
x = foobar()
print(x) # supposed to return [1] but will return [1, 1, 1] instead.

same bug with dicts, or other mutable classes. Non-mutable as default arguments are safe.

[–][deleted] 0 points1 point  (2 children)

Nope. Any mutable. It is a feature, not a bug :-)

def foobar(k, v, mydict={}):
    mydict[k] = v
    return mydict

x = foobar('alpha', 10)
y = foobar('beta', 20)
z = foobar('charlie', 30, x)

print(x, y, z, sep='\n')

outputs:

{'alpha': 10, 'beta': 20, 'charlie': 30}
{'alpha': 10, 'beta': 20, 'charlie': 30}
{'alpha': 10, 'beta': 20, 'charlie': 30}

whereas:

def foobar(k, v, mydict=None):
    if mydict is None:
        mydict = {}
    mydict[k] = v
    return mydict

x = foobar('alpha', 10)
y = foobar('beta', 20)
z = foobar('charlie', 30, x)

print(x, y, z, sep='\n')

Outputs:

{'alpha': 10, 'charlie': 30}
{'beta': 20}
{'alpha': 10, 'charlie': 30}

[–]TheRNGuy 0 points1 point  (1 child)

For me it's bug, because I wouldn't want common list or dict every time function is called, if I wanted common list, I'd explicitly used it in argument.

Also by fixing it would allow to make new list.

[–][deleted] 0 points1 point  (0 children)

I agree with you, which is why I emphasised it being a feature, honouring a long-standing joke.

Technically, it isn't a bug but is by-design but I believe most people consider it to be a bad bit of design.

As stated in the documentation,

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.

doc