[ python-Bugs-883987 ] Possible incorrect code generation

SourceForge.net noreply at sourceforge.net
Sun Jan 25 09:19:32 EST 2004


Bugs item #883987, was opened at 2004-01-24 22:52
Message generated for change (Comment added) made by billrubenstein
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=883987&group_id=5470

Category: Parser/Compiler
Group: Python 2.3
Status: Open
Resolution: None
Priority: 5
Submitted By: Bill Rubenstein (billrubenstein)
Assigned to: Nobody/Anonymous (nobody)
Summary: Possible incorrect code generation

Initial Comment:
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?

----------------------------------------------------------------------

>Comment By: Bill Rubenstein (billrubenstein)
Date: 2004-01-25 08:19

Message:
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.

----------------------------------------------------------------------

Comment By: Andrew I MacIntyre (aimacintyre)
Date: 2004-01-25 02:03

Message:
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.

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=883987&group_id=5470



More information about the Python-bugs-list mailing list