object() can't have attributes

Chris Angelico rosuav at gmail.com
Wed Dec 23 10:54:08 EST 2015


On Thu, Dec 24, 2015 at 2:49 AM, Irmen de Jong <irmen.NOSPAM at xs4all.nl> wrote:
> Hey, nice, didn't know about SimpleNamespace. I was about to suggest
> collections.namedtuple but that one is probably more than Neal asked for.
>
> Alternatively, you can still put attributes on a function, so this works as well (but I
> think it's rather ugly):
>
> thing = lambda: None
> thing.attr = 42
> vars(thing)   #  {'attr': 42}

If you can't use SimpleNamespace (eg you need to support pre-3.3), the
easiest way is an empty class:

class SimpleNamespace(object): pass

This will work in all versions of Python back to... I dunno,
2.something, maybe 1.x. Or, of course, you could lift the pure-Python
definition of SimpleNamespace from the docs and use that :)

ChrisA



More information about the Python-list mailing list