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

In strict mode, Mypy complains about finding attribute on union. [union-attr] #15099

Closed
amirsoroush opened this issue Apr 21, 2023 · 4 comments
Closed
Labels
bug mypy got something wrong

Comments

@amirsoroush
Copy link

Bug Report

Despite assigning a correct type, Mypy complains about finding an attribute when using --strict flag.

To Reproduce

var: int | None
var = 20

def fn() -> int:
    return var.bit_length()

print(fn())

Expected Behavior

Is to see "No Issue".

Actual Behavior

main.py:5: error: Item "None" of "Optional[int]" has no attribute "bit_length"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.2.0
  • Mypy command-line flags: --strict
  • Python version used: 3.10.6, 3.11, 3.12
@amirsoroush amirsoroush added the bug mypy got something wrong label Apr 21, 2023
@erictraut
Copy link

This is a duplicate of #2608.
is unsafe in the general case. Consider the following minor change to your code, which crashes at runtime.

var: int | None
var = 20

def fn() -> int:
    return var.bit_length()

var = None

print(fn())

@JelleZijlstra
Copy link
Member

Agree, mypy is correct here. Even if we change the behavior in #2608, this is a global variable, where it is even harder to reliably narrow the value.

@JelleZijlstra JelleZijlstra closed this as not planned Won't fix, can't repro, duplicate, stale Apr 21, 2023
@amirsoroush
Copy link
Author

@erictraut Reasonable. Thanks for explaining that case. So here it's better to remove the type hint for that global right?

@erictraut
Copy link

Yes, you could remove the type annotation. Another option is to add an assert within the inner scope (assert var is not None) to document your assumption for the type checker.

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

No branches or pull requests

3 participants