Use of lambda functions when connecting to Qt signals #131
Labels
enhancement
New feature or request
implementation suggestion
A suggestion for how a feature could be implemented
refactor
Code that needs to be restructured or cleaned up
I've noticed that across the codebase, signals are connected using
lambda
functions. While they certainly work, and can seem like a good solution for properly connecting signals to functions (especially with arguments), they do have some downsides.Memory safety
Lambda functions can cause QWidgets to not be properly garbage collected. (See this forum post and this StackOverflow thread). This can lead to some unexpected behavior and/or the application consuming more resources than expected.
Code cleanliness/readability
While it's true that
does work,
is functionally equivalent, along with being cleaner and easier to read. Additionally, while lambda functions can be extremely useful in the right situations, they can over-complicate what would otherwise be a simple operation.
Fix
Simple cases can just drop the lambda and actual function call in favor of a reference to the function. This is actually the intended way to use signals (see this example from the Qt for Python docs).
Example:
More complicated cases (ex: a function needs to be called with specific arguments) can be replaced with
functools.partial
, which is part of the Python standard library.partial
creates a "partial" function call, with pre-filled arguments.Example:
The text was updated successfully, but these errors were encountered: