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
I will use lambda
obj = lambda: None
obj.s = 'abb'
obj.i = 122
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))
Another obvious hack:
class foo1: x=3; y='y'
class foo2: y=5; x=6
print(foo1.x, foo2.y)
But for your exact usecase, calling a function with anonymous objects directly, I don't know any one-liner less verbose than
myfunc(type('', (object,), {'foo': 3},), type('', (object,), {'foo': 4}))
Ugly, does the job, but not really.
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
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