The filter value in an array of Python objects in the general case using a lambda function as a string

I am working on a general structure, and at some point I am trying to filter the variables in a general way. Take, for example, the following class:

class X:
    def __init__(self, val):
        self.val = val

Then I have an array of objects with arbitrary values val:

arr = [X("1"), X("2"), X("2"), X("3"), X("foo"), X("5"), X("3")]

My goal is to have a function that accepts a lambda function and variable names as strings (since they are provided by the user), which is currently implemented as follows:

def process(lambda_f_str, var_str):
    # should return [1, 2, 3, 5]
    return list(set(filter(lambda x: x, map(eval(lambda_f_str), eval(var_str)))))

I want to be able to call this method with a given line of a lambda function, which will return me only the unique integer values ​​of these objects (in this example, I would expect [1 2 3 5]order does not matter).

- :

process("lambda x: x.val if isinstance(x.val, int) else None", "arr")

, ( , , ).

try:
    int(x)
except:
    # do something if not an int

, -... ? , , .

, , . process, , , .

+3
2

?

f = lambda x: x.val if isinstance(x.val, int) else (int(x.val) if isinstance(x.val, basestring) and x.isdigit() else None)

100% , . 123L, Python.

0

...

s = "lambda x: int(x.val) if x.val.isdigit( ) else None"
print process(s, "arr")

...

[1, 2, 3, 5]

, .isdigit( ) , .

0

All Articles