Search code examples
pythonanonymous-types

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.


Solution

  • 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