python - coding style: lightweight/simplest way to create instances supporting attribute assignment? -
i have create result object instance return complex values functions , wonder what's nice pythonic approach.
i aware of closely related attribute-assignment-to-built-in-object, asking why needs hack subclass workaround use 'object'. understand why already. asking instead if there existing support in standard library avoid using 'object' , subclass hack, either through existing class or function.
what's lightest, pythonic way instantiate instance supports attribute assignment?
i ok pointed right subclassing 'object' answer. it's no big deal - want know if had missed cleaner approach supported standard library or builtins.
sample of trying do:
try: returnval = object() returnval.foo = 1 returnval.bar = 2 print "\n\nsuccess %s" % (returnval), vars(returnval), "has __slots__:", hasattr(returnval, "__slots__"), "has __dict__:", hasattr(returnval, "__dict__") except exception, e: print "\n\nfailure %s:%s" % (returnval, e), "has __slots__:", hasattr(returnval, "__slots__"), "has __dict__:", hasattr(returnval, "__dict__")
this fails, expected,
failure <object object @ 0x102c520a0>:'object' object has no attribute 'foo' has __slots__: false has __dict__: false
i not surprised. 'object' bare stub, , not allow attribute assignment because has no __dict__.
instead have declare placeholder class. there cleaner way?
try: class dummy(object): pass returnval = dummy() returnval.foo = 1 returnval.bar = 2 print "\n\nsuccess %s" % (returnval), vars(returnval), "has __slots__:", hasattr(returnval, "__slots__"), "has __dict__:", hasattr(returnval, "__dict__") except exception, e: print "\n\nfailure %s:%s" % (returnval, e), "has __slots__:", hasattr(returnval, "__slots__"), "has __dict__:", hasattr(returnval, "__dict__")
this gives:
success <__main__.dummy object @ 0x102d5f810> {'foo': 1, 'bar': 2} has __slots__: false has __dict__: true
using dummy/myclass approach avoids these problems, gives off mild code smell litter modules dummy classes.
things not work/are not satisfactory:
dictionaries. avoid if used dict instead, lose simple returnval.foo access.
attrdict implementations perhaps? come in 3rd party packages, not in standard lib.
mocks. not want using here, because not testing code , want exception thrown if returnval.foo not exist.
module/class attribute assignment. yes, assign attribute existing object in namespace, class or module declaration. assigning attributes singleton , successive function calls clobber each other.
a lightweight way use function container
>>> foo = lambda: 0 >>> foo.bar = 'bar' >>> foo.baz = 'baz'
if making bunch of immutable objects same attributes collections.namedtuple
more appropriate
>>> foo = namedtuple("foo", "bar, baz") >>> foo = foo('bar', 'baz') >>> foo.bar 'bar' >>> foo.baz 'baz'
Comments
Post a Comment