Should You Name Lambdas in Python?
Lambda expressions provide a concise and convenient way to define anonymous functions in Python. However, it is often tempting to assign names to lambdas within functions for code reuse and specific functionality.
Critique of Naming Lambdas
While this practice may seem convenient, it is generally considered non-Pythonic and goes against the recommendation of PEP8. As PEP8 states:
"Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier."
The rationale behind this recommendation is that defining a lambda as a function:
Example
Consider the example function provided in the question:
def fcn_operating_on_arrays(array0, array1): indexer = lambda a0, a1, idx: a0[idx] + a1[idx] # ... indexed = indexer(array0, array1, indices) # ...
Instead of using a named lambda, it is more Pythonic to define a separate, explicitly named function:
def index_array(a0, a1, idx): return a0[idx] + a1[idx] def fcn_operating_on_arrays(array0, array1): # ... indexed = index_array(array0, array1, indices) # ...
Conclusion
While assigning names to lambdas may seem useful in certain situations, it is not recommended. Instead, follow the Pythonic principle of using explicit function definitions to maintain clarity, readability, and adherence to best practices.
The above is the detailed content of To Name or Not to Name: When Should You Assign Names to Lambdas in Python?. For more information, please follow other related articles on the PHP Chinese website!