Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detecting possible NameError: name 'var' is not defined #13347

Closed
ashrub-holvi opened this issue Sep 13, 2024 · 2 comments
Closed

Detecting possible NameError: name 'var' is not defined #13347

ashrub-holvi opened this issue Sep 13, 2024 · 2 comments
Labels
type-inference Requires more advanced type inference.

Comments

@ashrub-holvi
Copy link

ashrub-holvi commented Sep 13, 2024

Hi,

Idea for a rule, PyCharm highlighting it, but don't see anything in ruff

file test.py:

# Copyright (c) 2021-2023 Mr XXX <e@ma.il>
"""The docs."""


class MyError(Exception):
    """The exception."""


def func() -> str:
    """Something.

    Raises:
        MyError: desc.

    """
    raise MyError


try:
    some_var = func()
except MyError as exception:
    if hasattr(exception, "message"):
        some_var = "something"
    # some_var is not defined in else case

print(some_var)  # noqa: T201

execution and ruff check:

$ python3 test.py 
Traceback (most recent call last):
  File "/.../test.py", line 26, in <module>
    print(some_var)  # noqa: T201
          ^^^^^^^^
NameError: name 'some_var' is not defined

$ ruff check --preview --isolated --select ALL test.py
...
All checks passed!

version: ruff 0.6.4

@MichaReiser
Copy link
Member

MichaReiser commented Sep 13, 2024

Hi @ashrub-holvi

Correctly modelling try-except is surprisingly hard. @AlexWaygood is currently implementing just that (see #13338) for red knot, our new static analysis backend that eventually will power ruff. However, it will take us a while until we get there.

If you're open to using typed Python, consider using pyright or mypy (until we release red knot ;)). They both should be able to catch this kind of error.

@MichaReiser MichaReiser added the type-inference Requires more advanced type inference. label Sep 13, 2024
@MichaReiser
Copy link
Member

I'll close this issue for now because there's no "easy" fix to add this behavior to Ruff other than re-implementing what we're building for red knot.

@MichaReiser MichaReiser closed this as not planned Won't fix, can't repro, duplicate, stale Sep 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-inference Requires more advanced type inference.
Projects
None yet
Development

No branches or pull requests

2 participants