Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 431
mike Avatar asked Mar 16 '09 21:03

mike


People also ask

Can an object be anonymous?

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.

Does Python have anonymous classes?

Python does not have anonymous functions, but they have dictionaries, and they work just as well.

What is the use of anonymous object?

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.

What is true about anonymous object?

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.


2 Answers

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 
like image 104
Nerdmaster Avatar answered Sep 22 '22 23:09

Nerdmaster


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 
like image 44
DzinX Avatar answered Sep 22 '22 23:09

DzinX