Issue 883987: Possible incorrect code generation (original) (raw)

Issue883987

Created on 2004-01-25 04:52 by billrubenstein, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg19813 - (view) Author: Bill Rubenstein (billrubenstein) Date: 2004-01-25 04:52
class test: defaultsclass = {'x': ['xxx'], 'y': ['yyy']} def __init__(self): for k, v in self.defaultsclass.items(): print 'setting from class table: ' + k + ':' + str(v) self.__dict__[k] = v def __str__(self): return str([k + ':' + str(v) for k, v in self.__dict__. items()]) print 'start' t = test() t.x.append('123') t.y.append('123') print 't:\n%s' % t print 'defaultsclass' for k, v in test.defaultsclass.items(): print 'k: %s; v:%s' % (k, str(v)) ********result************* start setting from class table: y:['yyy'] setting from class table: x:['xxx'] t: ["y:['yyy', '123']", "x:['xxx', '123']"] defaultsclass k: y; v:['yyy', '123'] k: x; v:['xxx', '123'] *************************** I don't see any code which modifies the defaultsclass dictionary (a class variable?) but it is clearly getting modified. Is there something I don't understand here?
msg19814 - (view) Author: Andrew I MacIntyre (aimacintyre) * (Python triager) Date: 2004-01-25 08:03
Logged In: YES user_id=250749 This is not a bug. While the defaultsclass dictionary is not getting modified, the lists that are its values are. To get the semantics you seem to expect, you should use self.__dict__[k] = v[:] instead of self.__dict__[k] = v in your __init__() method, which will clone your defaultsclass values when the instances are initialised.
msg19815 - (view) Author: Bill Rubenstein (billrubenstein) Date: 2004-01-25 14:19
Logged In: YES user_id=959527 Thanks for the explanation. I'm pretty new to Python, have coded in a number of different languages (some using referencing semantics) but just couldn't sort this one out without help. As a lanugage, Python is near the top of my list. It is simple, elegent and useful for solving all sorts of problems -- a real winner.
History
Date User Action Args
2022-04-11 14:56:02 admin set github: 39863
2004-01-25 04:52:08 billrubenstein create