up:: [[Python MOC]] tags:: #on/programming # Python Lambda Functions Lambda functions are Python's implementation of [[Anonymous Functions]]. ## Simple Example A normal function would be defined like this: ```python def half(x): return x / 2 ``` The equivalent lambda function would be: ```python lambda x: x / 2 ``` - Three parts to lambda expression: - *keyword*: `lambda` - *bound variable*: `x` - *body*: `x / 2` - A **bound variable** is an argument to a lambda function. A **free variable** is either a constant or a variable defined in the enclosing scope of the function. To call the lambda function: ```python >>> (lambda x: x / 2)(6) 3 ``` Lambda functions are expressions, so you can name them: ```python >>> half = lambda x: x / 2 >>> half(6) 3 ``` - Multi-argument functions have arguments separated by a comma, but without parentheses surrounding them --- - You can call a lambda function immediately when it is defined: ```python >>>(lambda x: x / 2)(6) 3 ``` - This is called an Immediately Invoked Function Expression (IIFE) - Commonly-used pattern in JavaScript - Python does not encourage doing this; it's just a result of lambdas being callable - Lambdas are often used with [[Higher Order Functions]], which take one or more functions as arguments or return one or more functions --- ## Differences Between Lambdas and Regular Functions - They produce the same bytecode, except regular functions are seen with their names while lambda functions are just seen as `<lambda>` - In tracebacks, a regular function is shown with its name. Lambda functions are just shown as `<lambda>`, which can make debugging more difficult. - Lambda functions can't include statements in the body, only expressions - Lambdas are written as a single line - Lambdas do not support type annotations - Lambdas can be immediately invoked (IIFE) - You can't decorate a lambda with the `@decorator` syntax, though you can apply [[Python Decorators|decorators]] to lambdas - In a normal function, free variables are bound at definition time. In lambdas, they are bound at runtime. ## Code Smells There are a few different ways that lambdas can be abused. The following are examples of lambda usages that should be avoided: - Raising an exception inside a lambda function - Writing class methods as lambda functions ## References Real Python. “How to Use Python Lambda Functions – Real Python.” Accessed August 1, 2024. [https://realpython.com/python-lambda/](https://realpython.com/python-lambda/).