Nick Coghlan <[EMAIL PROTECTED]> wrote: ...
Michael Spencer also posted an interesting idea recently about setting up a view of an existing dictionary, rather than as a separate object:
class attr_view(object): def __init__(self, data): object.__setattr__(self, "_data", data) def __getattr__(self, attrname): return self._data[attrname] def __setattr__(self, attrname, value): self._data[attrname] = value
Wasted indirection, IMHO. A better implementation:
class attr_view(object): def __init__(self, data): self.__dict__ = data
Alex
Yeah, I caught your comment in the other thread. It was something I'd wondered about, but never followed up .
And any time you want real dictionary behaviour, a quick call to "vars(x)" will do nicely.
I think the idea definitely deserves mention as a possible implementation strategy in the generic objects PEP, with the data argument made optional:
class namespace(object): def __init__(self, data=None): if data is not None: self.__dict__ = data # Remainder as per Bunch in the PEP. . .
Py> result = namespace() Py> result.x = 1 Py> result.y = 2 Py> vars(result) {'y': 2, 'x': 1} Py> gbls = namespace(globals()) Py> gbls.result <__main__.namespace object at 0x00B2E370> Py> gbls.result.x 1 Py> gbls.result.y 2 Py> gbls.gbls <__main__.namespace object at 0x00B2E410>
This does mean construction using keywords or a sequence of pairs requires an extra call to dict() at the invocation point. However, it means that the class can also be used to manipulate an existing dictionary, which the current PEP version doesn't allow.
namespace(existing_dict) would mean that the namespace should manipulate the original dictionary.
namespace() would create a new, initially empty, dict to work on.
namespace(dict(<whatever>)) would create a new, non-empty, dict based on the standard arguments to the dictionary constructor.
Cheers, Nick.
-- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list