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 ().

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)