namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP
Nick Coghlan
ncoghlan at iinet.net.au
Sat Feb 12 23:50:31 EST 2005
Nick Coghlan wrote:
> class Namespace(object):
> # etc
> def _update_dict(self, other):
> for k in other:
> setattr(self, k, other[k])
This doesn't work, as it doesn't allow the sequence of 2-tuples. So I copied the
relevant check for a keys() attribute from dict.update:
def _update_dict(self, other):
"""Allow subclasses to easily override handling of dict updates
Also allows dotted names in the source to be handled correctly
Uses the "keys" attribute to identify mappings
"""
try:
items = other.keys()
except AttributeError:
for k, v in other:
setattr(self, k, v)
else:
for k in items:
setattr(self, k, other[k])
Another change I made was to the Record class. It now uses __new__ to initialise
the instance dictionary with the defaults from the subclass definition, leaving
__init__ free to be used to invoke update() like it is for a standard namespace:
Py> from namespaces import Record
Py> class Example(Record):
... a = 1
... b = ""
... class _sub_sf(Record):
... c = 3
... def _sub_calc(): return "Calculated value!"
...
Py> x = Example()
Py> x
Example(a=1, b='', calc='Calculated value!', sf=_sub_sf(c=3))
Py> x = Example(a=3)
Py> x
Example(a=3, b='', calc='Calculated value!', sf=_sub_sf(c=3))
Py> x = Example([("sf.c", 5)], a=3, b="altered")
Py> x
Example(a=3, b='altered', calc='Calculated value!', sf=_sub_sf(c=5))
Py> x = Example({"sf.c": 5}, a=3, b="altered")
Py> x
Example(a=3, b='altered', calc='Calculated value!', sf=_sub_sf(c=5))
I also moved the module to my normal site:
http://boredomandlaziness.skystorm.net/misc/namespaces.py
Steven: Feel free to pick through this for anything you want to add to the PEP.
That's why I'm posting it, after all :)
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
More information about the Python-list
mailing list