A generic object to hold data in python
From: http://stackoverflow.com/questions/1878710/struct-objects-in-python
A most concise way to make “a generic object to which you can assign/fetch attributes” is probably:
item = lambda: 0 item.len = 4 item.data = list(map(int, input().rstrip().split(" ")))
At first, this boggled my mind. But it’s actually simple. The
lambda
creates a function object; this one happens to be a trivial function that returns 0. Function objects have certain attributes, among them afunc_dict
member. This works because it works for any function object; you can bind values to names associated with any function object. I have used that to provide “enumerated” flags that can be used when calling the function:foo(0, foo.ALTERNATE_MODE)
This made-up example shows calling a function with an optional flag that requests some sort of alternate mode. – steveha Dec 31 ’09 at 22:09
More about python lambda function: (from: http://www.secnetix.de/olli/Python/lambda_functions.hawk)
Python supports the creation of anonymous functions at runtime, using a construct called “lambda”. This is not exactly the same as lambda in functional programming languages, but it is a very powerful concept that’s well integrated into Python and is often used in conjunction with typical functional concepts like filter() , map() and reduce() .
>>> def f (x): return x**2 ... >>> print f(8) 64 >>> >>> g = lambda x: x**2 >>> >>> print g(8) 64