Unnecessary lambda¶
ID: py/unnecessary-lambdaKind: problemSecurity severity: Severity: recommendationPrecision: highTags: - quality - maintainability - useless-codeQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
A lambda that calls a function without modifying any of its parameters is unnecessary. Python functions are first class objects and can be passed around in the same way as the resulting lambda.
Recommendation¶
Remove the lambda, use the function directly.
Example¶
In this example a lambda is used unnecessarily in order to pass a method as an argument tocall_with_x_squared.
importmathdefcall_with_x_squared(x,function):x=x*xreturnfunction(x)printcall_with_x_squared(2,lambdax:math.factorial(x))
This is not necessary as methods can be passed directly. They behave as callable objects.
importmathdefcall_with_x_squared(x,function):x=x*xreturnfunction(x)printcall_with_x_squared(2,math.factorial)
References¶
Python:lambdas.