I'm working on a generic framework, and at some point I'm trying to filter variables in a generic manner. Take for example the following class:
class X:
def __init__(self, val):
self.val = val
Then I have an array of objects with arbitrary val
values:
arr = [X("1"), X("2"), X("2"), X("3"), X("foo"), X("5"), X("3")]
My goal is to have a function which takes a lambda function and a variable names as strings (because they are user provided), 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 lambda function string that will return me only the unique integer values of these objects (In this example I'd expect [1 2 3 5]
, the order doesn't matter).
I've tried something like this:
process("lambda x: x.val if isinstance(x.val, int) else None", "arr")
But this doesn't work since the integers are still passed as strings in my array (and I have no control over that, this is user-provided so I can't make any assumption).
I wanted to do the equivalent of
try:
int(x)
except:
# do something if not an int
But I don't think you can do that in a lambda function ... can you? At least I haven't found out how.
I'd be interested to see how I can write this lambda to do this filtering in a generic manner. I'd rather avoid changing the process
method since this is a generic function which does other things not included in this sample code for the sake of brevity.
isint()
function and doprocess("lambda x: x.val if isint(x.val) else None", "arr")
? – Lev Levitsky May 11 '12 at 18:00isint
. Of course this could be part of documentation or comment to let the user know, but I wanted to know if there's a better way to do this, otherwise that's probably what I'll have to do. – Charles Menguy May 11 '12 at 18:02