astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
33.15k stars 1.11k forks source link

Lint for closure that do not capture anything ? #14603

Open Carreau opened 23 hours ago

Carreau commented 23 hours ago

Hi,

Thanks for ruff – sorry if I missed it in ruff docs and already existing opened and closed issues; but is there any hints for function closure that do not capture any variables ?

I've came across a few project recently where the variable the function was closed over was removed; and the closure could have been moved outside of it's defining function as a util function; and was wondering if this is something ruff could detect.

Thanks.

MichaReiser commented 23 hours ago

Hi @Carreau

This is something that Ruff could detect well in most cases. My concern with such a rule is that there are other reasons for nested functions. For example, nesting a function might be a deliberate choice to reduce the function's visibility (make it inaccessible from outside). I haven't written enough Python code myself to judge how common this is in Python but it's a very common pattern in JavaScript.

Carreau commented 22 hours ago

Thanks for the quick answer;

I do understand and I was hopping there could be a # noqa: number in these case; it's also – sometime – I think a matter of taste.

IMHO; reduce visibility can be achieve by making the functions private (start name with underscore; ; don't list is on __all__, static method on class); which is always better for unit-testing and readability anyway.

I think non-capturing closures, that are returned from function should likely also be exempt from this.

I agree that for the little JS I write; there are more often locally defined functions; but Js is also better suited at functional an have an easier way of defining multiline functions.