Naming Anonymous Functions in Python: A Pythonic Approach
In Python, lambda expressions provide a convenient way to create anonymous functions for quick and concise code. However, the question arises: is it pythonic to name these lambdas within functions?
According to PEP8 style guidelines, it is discouraged to assign lambda expressions directly to identifiers. This practice blurs the distinction between anonymous and named functions, making debugging and code readability more difficult.
When to Avoid Naming Lambdas
As a rule of thumb, avoid naming lambdas if the functionality is specific to the enclosing function and not required elsewhere in the codebase. In such cases, the simplicity and brevity of lambdas outweigh the need for naming them.
Alternatives to Named Lambdas
When the functionality warrants being reused or shared, consider the following alternatives:
Example
Consider the following code:
def fcn_operating_on_arrays(array0, array1): indexer = lambda a0, a1, idx: a0[idx] + a1[idx] # codecodecode indexed = indexer(array0, array1, indices) # codecodecode in which other arrays are created and require `indexer` return the_answer
Instead of naming the lambda expression indexer, it could be rewritten using a separate function:
def indexer(a0, a1, idx): return a0[idx] + a1[idx] def fcn_operating_on_arrays(array0, array1): indexed = indexer(array0, array1, indices) # codecodecode in which other arrays are created and require `indexer` return the_answer
The above is the detailed content of Should You Name Anonymous Lambda Functions in Python?. For more information, please follow other related articles on the PHP Chinese website!