Shortest way of creating an object with arbitrary attributes in Python?

type('', (), {})() will create an object that can have arbitrary attributes.

Example:

obj = type('', (), {})()
obj.hello = "hello"
obj.world = "world"
print obj.hello, obj.world   # will print "hello world"

type() with three arguments creates a new type.

  • The first argument '' is the name of the new type. We don't care about the name, so we leave it empty.

  • The second argument () is a tuple of base types. Here object is implicit.

  • The third argument is a dictionary of attributes of the new object. We start off with no attributes so it's empty {}.

In the end we instantiate a new instance of this new type with ().


Use collections.namedtuple.

It works well.

from collections import namedtuple
Data = namedtuple( 'Data', [ 'do_good_stuff', 'do_bad_stuff' ] )
options = Data( True, False )

This is the shortest way I know

>>> obj = type("myobj",(object,),dict(foo=1,bar=2))
>>> obj.foo
1
>>> obj.bar
2
>>> 

using dict instead of {} insures your attribute names are valid

>>> obj = type("myobj",(object,),{"foo-attr":1,"bar-attr":2})
>>> obj.foo-attr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'myobj' has no attribute 'foo'
>>>

The original code can be streamlined a little by using __dict__:

In [1]: class data:
   ...:     def __init__(self, **kwargs):
   ...:         self.__dict__.update(kwargs)
   ...: 

In [2]: d = data(foo=1, bar=2)

In [3]: d.foo
Out[3]: 1

In [4]: d.bar
Out[4]: 2

In Python 3.3 and greater, this syntax is made available by the types.SimpleNamespace class.

Tags:

Python