In Python 2.6, I want to do:
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
This clearly isn't the syntax. Is it possible to perform an if
in lambda
and if so how to do it?
In Python 2.6, I want to do:
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
This clearly isn't the syntax. Is it possible to perform an if
in lambda
and if so how to do it?
You can easily raise an exception in a lambda, if that's what you really want to do.
def Raise(exception):
raise exception
x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))
Is this a good idea? My instinct in general is to leave the error reporting out of lambdas; let it have a value of None and raise the error in the caller. I don't think this is inherently evil, though--I consider the "y if x else z" syntax itself worse--just make sure you're not trying to stuff too much into a lambda body.
Lambdas in Python are fairly restrictive with regard to what you're allowed to use. Specifically, you can't have any keywords (except for operators like and
, not
, or
, etc) in their body.
So, there's no way you could use a lambda for your example (because you can't use raise
), but if you're willing to concede on that… You could use:
f = lambda x: x == 2 and x or None
You can also use Logical Operators to have something like a Conditional
func = lambda element: (expression and DoSomething) or DoSomethingIfExpressionIsFalse
You can see more about Logical Operators here
An easy way to perform an if in lambda is by using list comprehension.
You can't raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:
f = lambda x: print(x) if x==2 else print("exception")
Another example:
return 1 if M otherwise 0
f = lambda x: 1 if x=="M" else 0