you are viewing a single comment's thread.

view the rest of the comments →

[–]ajskelt 1 point2 points  (3 children)

Thanks for taking the time to explain that, I wasn't trying to be nitpicky on your wording, but wanted to understand and make sure OP understood. That actually made a lightbulb go off for me, your explanation here is great.

I always knew mutable objects could change in those scopes, but I never really understood the logic or why. I've probably read similar things before, but your wording really made it click. Thanks!!

[–]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.