[Python-ideas] Shorthand syntax for get/set/delattr (was Re: Dict-like object with property access)

Nick Coghlan ncoghlan at gmail.com
Mon Feb 6 02:41:38 CET 2012

On Mon, Feb 6, 2012 at 11:07 AM, Mathias Panzenböck
<grosser.meister.morti at gmx.net> wrote:

This is a good start, but still has a few issues.

>        def get(self, key, default=None):
>                try:
>                        return getattr(self.obj, key, default)
>                except AttributeError:
>                        raise KeyError(key)

This will never raise KeyError. It needs to use a dedicated sentinel
object so it can tell the difference between "default=None" and
"default not supplied" and invoke getattr() accordingly.

>        def keys(self):
>                return iter(dir(self.obj))
>        def values(self):
>                for key in dir(self.obj):
>                        yield getattr(self.obj, key)
>        def items(self):
>                for key in dir(self.obj):
>                        yield key, getattr(self.obj, key)

These 3 methods should return views with the appropriate APIs rather
than iterators.

>        def __repr__(self):
>                return repr(dict(self))

The appropriate output for str() and repr() is definitely open for
question. Interaction with serialisation APIs such as pickle and json
will also need investigation.

These kinds of question are why I think it is well-worth exploring
this concept on PyPI.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list