org.sonar.l10n.py.rules.python.S6661.html Maven / Gradle / Ivy
The newest version!
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:
- 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.
- 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.
- 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.
- 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 PEP8.
How to fix it
Use function definition using def
statement instead of assigning lambda to a variable.
Code examples
Noncompliant code example
def foo():
multiply = lambda x, y: x * y # Noncompliant
Compliant solution
def foo():
def multiply(x, y):
return x * y
...
Resources
Documentation
- Python Documentation - Defining Functions
- Style Guide for Python Code - PEP8
© 2015 - 2025 Weber Informatics LLC | Privacy Policy