python newbie - question about lexical scoping

hdante hdante at gmail.com
Sun Dec 2 12:52:27 EST 2007


On Dec 1, 11:31 pm, "Matt Barnicle" <ma... at wageslavery.org> wrote:
> >> On Dec 1, 4:47 pm, Matt Barnicle <ma... at wageslavery.org> wrote:
> > aye yaye aye...  thanks for the pointers in the right direction..  i
> > fiddled around with the code for a while and now i've reduced it to the
> > *real* issue...  i have a class dict variable that apparently holds its
> > value across instantiations of new objects..  the problem can be
> > illustrated in the following much simpler code:
>
> >>>> class foo():
> > ...     bar = { 'baz': 'bing' }
> > ...
> >>>> a = foo()
> >>>> a.bar
> > {'baz': 'bing'}
> >>>> a.bar['baz'] = 'bong'
> >>>> a.bar
> > {'baz': 'bong'}
> >>>> b = foo()
> >>>> b.bar
> > {'baz': 'bong'}
>
> ok, i see...  python has a concept i'm not accustomed to which i found
> described here:
>
> http://zephyrfalcon.org/labs/python_pitfalls.html
> 4. Class attributes vs instance attributes
>
> so i'm sure what is going on is obvious to experienced python
> programmers...  i'm not really sure how to get around this though.  i'll
> need to spend some time on reworking our models code i guess...  i
> inherited this from someone, and what he was trying to do was to set
> default values for objects representing tables (in kind of a simple ORM
> layer) and storing the values in a dict, and when the object is
> instantiated, the table is queried and the default dict values are
> overwritten.  so obviously this method is not going to work as such..
>
> sorry for the misdirection, i didn't quite understand at first..
>
> - m@


A trivial solution:

class foo:
	default_bar = { 'baz' : 'bong' }
	def __init__(self):
		self.bar = self.default_bar.copy()
		self.bar['woo'] = 'wee'

 Note: it's not necessary to reimplement an ORM. Try using Django (if
you need a complete solution) or Elixir (just the ORM).



More information about the Python-list mailing list