Supply condition in function call

Rustom Mody rustompmody at gmail.com
Thu Mar 26 00:02:03 EDT 2015


On Thursday, March 26, 2015 at 12:44:03 AM UTC+5:30, Gary Herron wrote:
> On 03/25/2015 10:29 AM, Manuel Graune wrote:
> > Hi,
> >
> > I'm looking for a way to supply a condition to an if-statement inside a
> > function body when calling the function. I can sort of get what I want
> > with using eval (see code below) but I would like to achieve this in a
> > safer way. If there is a solution which is safer while being
> > less flexible, that would be fine. Also, supplying the condition as a
> > string is not necessary. What I want to do is basically like this:
> >
> > def test1(a, b, condition="True"):
> >      for i,j in zip(a,b):
> >          c=i+j
> >          if eval(condition):
> >             print("Foo")
> >
> > test1([0,1,2,3],[1,2,3,4],"i+j >4")
> > print("Bar")
> > test1([0,1,2,3],[1,2,3,4],"c >4")
> > print("Bar")
> > test1([0,1,2,3],[1,2,3,4],"a[i] >2")
> > print("Bar")
> > test1([0,1,2,3],[1,2,3,4])
> >
> >
> 
> This is nicely done with lambda expressions:

The builtin function filter is for this (more or less).
Comprehensions are usually better than filter.

[And BTW
help(filter) in python2 is much better documention than in python3
]



More information about the Python-list mailing list