8000 Provide hint when Union type with None may not have been narrowed by angelawuuu · Pull Request #17178 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Provide hint when Union type with None may not have been narrowed #17178

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

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added checks that context is a MemberExpr before accessing its expr a…
…ttribute
  • Loading branch information
angelawuuu committed Apr 25, 2024
commit a102f95bc57535a5fd5dd8663f5da71d2d817f69
4 changes: 2 additions & 2 deletions mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,9 +534,9 @@ def has_no_attr(
if typ_format == '"None"':
if isinstance(context, NameExpr):
var_name = f" {context.name}"
elif isinstance(context.expr, NameExpr):
elif isinstance(context, MemberExpr) and isinstance(context.expr, NameExpr):
var_name = f" {context.expr.name}"
elif isinstance(context.expr, MemberExpr):
elif isinstance(context, MemberExpr) and isinstance(context.expr, MemberExpr):
var_name = f" {get_member_expr_fullname(context.expr)}"
Copy link
Member
@brianschubert brianschubert Sep 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This branch has some hiccups if the expression isn't strictly a dotted member expression:

class A:
    x: int | None

class B:
    a: A

[A()][0].x.bit_count()  # N: You can use "if None is not None" to guard against a None value
B().a.x.bit_count()     # N: You can use "if None.x is not None" to guard against a None value

I think two adjustments would be needed:

  1. check for get_member_expr_fullname returning None (and don't emit the note if it does)
  2. fix the case where get_member_expr_fullname returns a string with an embedded "None" (edit: fixed in #17848)

else:
var_name = " <variable name>"
Expand Down
0