69 lines
2.6 KiB
Plaintext

This rule raises an issue when a lambda is directly assigned to a variable.
== Why is this an issue?
Assigning a lambda to a variable is not inherently wrong or discouraged in Python. Lambdas are anonymous functions that can be useful for short and simple expressions or as function arguments. However, there are a few reasons why you might consider alternatives to assigning a lambda to a variable:
1. *Readability and clarity:* Lambdas can be concise, but they may become less readable as the expression or logic becomes more complex. For more complex or longer functions, using a regular named function defined with def can make the code more readable and self-explanatory.
2. *Reusability:* Lambdas are often used for one-off or small, isolated tasks. If you find that you need to reuse a piece of functionality in multiple places within your code or across modules, it is better to define a named function using def. This promotes code modularity and maintainability.
3. *Documentation:* Lambdas do not support docstrings, which are important for providing clear and comprehensive documentation for your functions. If you need to document the purpose, parameters, or behavior of a function, it is best to define a named function using def and include a docstring.
4. *Debugging and error handling:* Lambdas are anonymous functions, which means that when an error occurs during execution, the traceback will not provide a specific name associated with the lambda function. This can make it more challenging to identify and troubleshoot errors. Named functions defined with def provide more meaningful tracebacks.
Using a def statements rather than assigning lambdas to variable is also recommended by https://peps.python.org/pep-0008/[PEP8].
== How to fix it
Use function definition using `def` statement instead of assigning lambda to a variable.
=== Code examples
==== Noncompliant code example
[source,python,diff-id=1,diff-type=noncompliant]
----
def foo():
multiply = lambda x, y: x * y # Noncompliant
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
def foo():
def multiply(x, y):
return x * y
...
----
== Resources
=== Documentation
* Python Documentation - https://docs.python.org/3/tutorial/controlflow.html#defining-functions[Defining Functions]
* Style Guide for Python Code - https://peps.python.org/pep-0008/[PEP8]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Define function instead of this lambda assignment statement.
=== Highlighting
Primary: assignment statement
'''
== Comments And Links
(visible only on this page)
endif::env-github,rspecator-view[]