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

typing.Literal can not be correctly checked against if it was imported via wildcard import #489

Open
2 tasks done
xiaosiyu0603 opened this issue Sep 21, 2024 · 3 comments
Labels

Comments

@xiaosiyu0603
Copy link

xiaosiyu0603 commented Sep 21, 2024

Things to check first

  • I have searched the existing issues and didn't find my bug already reported there

  • I have checked that my bug is still present in the latest release

Typeguard version

4.3.0

Python version

3.11.5

What happened?

My code:

from typing import *
from typeguard import typechecked


@typechecked
def test(string: Literal["hi"] | Literal['hello']):
    return string


print(test("hi"))

Exception raised when running in python:

D:\Home\Desktop>python tgt.py
Traceback (most recent call last):
  File "D:\Home\Desktop\tgt.py", line 11, in <module>
    print(test("hi"))
          ^^^^^^^^^^
  File "D:\Home\Desktop\tgt.py", line 7, in test     
    def test(string: Literal["hi"] | Literal['hello']):
                             ^^^^
NameError: name 'hi' is not defined

How can we reproduce the bug?

Maybe run the code?

@agronholm
Copy link
Owner

This is caused by the wildcard import, the use of which is bad practice. If instead you do:

from typing import Literal

This works fine. The underlying problem is that the AST transformer looks for typing.Literal and special cases it, but as it can't see where Literal comes from, it doesn't special case Literal, and ends up removing the quotes.

@xiaosiyu0603
Copy link
Author

It works well, thanks a lot! 😀🙏

(It's a little hard for python programmers who lack professional background to discover such mistake.😂 Adding some warnings to the documentation might be helpful.)

@agronholm
Copy link
Owner

I'll think about that. This is a shortcoming of the library though, and it could some day be fixed. It wll involve nontrivial amounts of work though.

@agronholm agronholm changed the title typing.Literal can not be correctly checked typing.Literal can not be correctly checked against if it was imported via wildcard import Oct 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants