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.
Object expressions You can define them from scratch, inherit from existing classes, or implement interfaces. Instances of anonymous classes are also called anonymous objects because they are defined by an expression, not a name.
Python does not have anonymous functions, but they have dictionaries, and they work just as well.
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.
An anonymous object is essentially a value that has no name. Because they have no name, there's no way to refer to them beyond the point where they are created. Consequently, they have “expression scope”, meaning they are created, evaluated, and destroyed all within a single expression.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With