Is it possible to create anonymous objects in Python?
I'm debugging some Python that takes, as input, a list of objects, each with some attributes.
I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number.
Is there a more concise way than this?
x1.foo = 1
x2.foo = 2
x3.foo = 3
x4.foo = 4
myfunc([x1, x2, x3, x4])
Ideally, I'd just like to be able to say something like:
myfunc([<foo=1>, <foo=2>, <foo=3>, <foo=4>])
(Obviously, that is made-up syntax. But is there something similar that really works?)
Note: This will never be checked in. It's just some throwaway debug code. So don't worry about readability or maintainability.
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 Tetha's solution, but it's unnecessarily complex.
Here's 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
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)()
Have a look at this:
class MiniMock(object):
def __new__(cls, **attrs):
result = object.__new__(cls)
result.__dict__ = attrs
return result
def print_foo(x):
print x.foo
print_foo(MiniMock(foo=3))
Maybe you can use namedtuple to solve this as following:
from collections import namedtuple
Mock = namedtuple('Mock', ['foo'])
mock = Mock(foo=1)
mock.foo // 1