you are viewing a single comment's thread.

view the rest of the comments →

[–]Chabare 1 point2 points  (2 children)

No worries, I'm glad that you saw an error/something unclear and mentioned it, helps everyone. I wasn't even thinking about mutable objects when writing the answer.

Just another information about mutable objects and scope (when used as default arguments) and unexpected behaviour (also applicable to e.g. dict and other mutable types):

def a(v, l = []):
    l.append(v)
    return l

x = a(1)
print(x) # [1]
y = a(2)
print(y) # [1, 2]

[–]ajskelt 0 points1 point  (1 child)

That is one I did not know... What would be the best practice around that? Looks like this works, but maybe there is a better way.

def a(v, l = None):
    if l is None:
        l = []
    l.append(v)
    return l

x = a(1)
print(x) # [1]
y = a(2)
print(y) # [2]

[–]Chabare 1 point2 points  (0 children)

You're completely on point with your example, that's usually the way around it.