Is it possible to create anonymous objects in Python?

Is it possible to create anonymous objects in Python?

I found this: http://www.hydrogen18.com/blog/python-anonymous-objects.html, and in my limited testing it seems like it works:

>>> obj = type(,(object,),{foo: 1})()
>>> obj.foo
1

I like Tethas solution, but its unnecessarily complex.

Heres something simpler:

>>> class MicroMock(object):
...     def __init__(self, **kwargs):
...         self.__dict__.update(kwargs)
...
>>> def print_foo(x):
...     print x.foo
...
>>> print_foo(MicroMock(foo=3))
3

Is it possible to create anonymous objects in Python?

So brief, such Python! O.o

>>> Object = lambda **kwargs: type(Object, (), kwargs)

Then you can use Object as a generic object constructor:

>>> person = Object(name = Bernhard, gender = male, age = 42)
>>> person.name
Bernhard
>>>

EDIT: Well okay, technically this creates a class object, not an object object. But you can treat it like an anonymous object or you modify the first line by appending a pair of parenthesis to create an instance immediately:

>>> Object = lambda **kwargs: type(Object, (), kwargs)()

Leave a Reply

Your email address will not be published. Required fields are marked *