Reputation: 2502
I am trying to construct a python lambda function from either a single parameter or a list, and am unsure what syntax to use to build the lambda:
def check_classes_filter(*class):
return lambda x: isinstance(x, class) and isinstance(x, class[1]...)
The lambda should check if x is an instance of any number of classes that is passed to the function (either one or many).
Is there a general way to build functions from an arbitrary number of parameters in python, maybe as a kind of comprehension?
Upvotes: 1
Views: 75
Reputation: 54223
If you want to check that an object is an instance of any listed class, you don't need to define anything:
>>> isinstance('test', int)
False
>>> isinstance('test', str)
True
>>> isinstance('test', (int, str))
True
From isinstance
documentation :
If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types.
In your question, you mention if x is an instance of any number of classes that is passed to the function (either one or many)
, it would mean that you should or
instead of and
in your boolean logic. If you want to check that an object is an instance of every listed classes, see the answer with all
.
Upvotes: 2
Reputation: 117856
You could loop over your classes
args using all
.
def check_classes_filter(*classes):
return lambda x: all(isinstance(x, c) for c in classes)
>>> fun = check_classes_filter(str)
>>> fun('hello')
True
>>> fun = check_classes_filter(int, str)
>>> fun('hello')
False
Although I'd prefer just passing in a list
of classes
def check_classes_filter(classes):
return lambda x: all(isinstance(x, c) for c in classes)
and calling the function as
check_classes_filter([int, str])
Upvotes: 3