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

Don't replace string type annotations when module is only imported with TYPE_CHECKING #934

Closed
david-zwicker opened this issue Mar 2, 2024 · 2 comments

Comments

@david-zwicker
Copy link

pyupgrade aggressively replaces types that are given as strings, which breaks my code. Here's minimal code to demonstrate the problem:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import sympy

def f(sym: "sympy.Symbol"):
    import sympy
    ...

The idea is that the sympy package is a heavy import and I thus just want to import it lazily when necessary. Yet, I want to give proper types, which in principle is possible using strings. Additionally using the TYPE_CHECKING guard, mypy can still check the types.

The problem is that pyupgrade automatically changes the code to

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import sympy

def f(sym: sympy.Symbol):
    import sympy
    ...

which doesn't run anymore since sympy.Symbol is not available in a normal context (when TYPE_CHECKING is False).
Is there a work-around with which I can prevent this problem?

@asottile
Copy link
Owner

asottile commented Mar 2, 2024

I assume you closed this because you were wrong?

@david-zwicker
Copy link
Author

Yeah, the issue was that my IDE is not smart enough about this and marked an error. I mistakenly thought that python had a problem with the undefined sympy, but apparently it is smarter than I thought :) All good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants