New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
default value in constructor not unique across objects #53008
Comments
After debugging for a while I finally released that I stumbled across a Python bug (at least I believe it is). Here is a proof of concept that produces the issue: !/usr/bin/python class blah:
def __init__(self, items=[]):
self.items = items
a = blah()
b = blah()
a.items.append("apples")
b.items.append("oranges") print a.items and here is the output when the program is run: root@x: as you can see the 'items' reference is the same for both objects even though they are different objects. I checked the manual and I couldn't find anything explaining such behavior. Can this possibly be correct? My python info: Python 2.5.2 (r252:60911, Jan 20 2010, 21:48:48) |
This is not a bug, it's how Python works. Default values are computed at function definition time, so there's only one list across all the function invocations. |
Here is the explanation from Python Language Reference 7.6: Function Definitions def whats_on_the_telly(penguin=None):
if penguin is None:
penguin = []
penguin.append("property of the zoo")
return penguin
""" |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: