ty icon indicating copy to clipboard operation
ty copied to clipboard

don't emit diagnostics about "shadowing" when assignment target is not a local variable

Open SerTetora opened this issue 3 weeks ago • 7 comments

Summary

from configparser import ConfigParser

cfgparser = ConfigParser()
cfgparser.optionxform = str  # <--- Should be allowed, per Python docs

Ref. https://docs.python.org/3/library/configparser.html#configparser.ConfigParser.optionxform

ty

Implicit shadowing of function `optionxform` (invalid-assignment) [Ln 4, Col 1]

pyrefly

ERROR sandbox.py:4:25-28: `type[str]` is not assignable to attribute `optionxform` with type `BoundMethod[ConfigParser, (self: ConfigParser, optionstr: str) -> str]` [[bad-assignment](https://pyrefly.org/en/docs/error-kinds/#bad-assignment)]
  Positional parameter name mismatch: got `object`, want `optionstr`

pyright

Cannot assign to attribute "optionxform" for class "ConfigParser"
  No overloaded function matches type "(optionstr: str) -> str"  (reportAttributeAccessIssue)

mypy

main.py:4: error: Cannot assign to a method  [method-assign]
main.py:4: error: Incompatible types in assignment (expression has type "type[str]", variable has type "Callable[[str], str]")  [assignment]
Found 2 errors in 1 file (checked 1 source file)

Version

0.0.2

SerTetora avatar Dec 17 '25 09:12 SerTetora

Thank you for reporting this.

Our error message is different from the other type checkers, but it looks like all other type checkers also issue an error. If this should really be allowed, maybe it's a problem with the stubs for this attribute?

sharkdp avatar Dec 17 '25 09:12 sharkdp

Thanks for the feedback!

If this should really be allowed, maybe it's a problem with the stubs for this attribute?

What would you recommend to do in this case?

SerTetora avatar Dec 17 '25 09:12 SerTetora

I think this would be an appropriate place to use a suppression comment (# type: ignore or `# ty: ignore, see https://docs.astral.sh/ty/suppression/).

sharkdp avatar Dec 17 '25 10:12 sharkdp

If we believe that there's a bug in the stubs, then a report should be filed over at typeshed (if there isn't already an issue there regarding this)

AlexWaygood avatar Dec 17 '25 10:12 AlexWaygood

Looks like this was discussed before:

  • https://github.com/python/typeshed/issues/1857
  • https://github.com/python/mypy/issues/5062
  • https://github.com/python/mypy/issues/708

sharkdp avatar Dec 17 '25 10:12 sharkdp

Closing this for now, let me know if anyone thinks there is something we could do in ty to address this.

sharkdp avatar Dec 18 '25 11:12 sharkdp

Our diagnostic is bad here and should be improved; the logic we attempt to use for detecting implicit shadowing of a function or class wrongly fires on assignments like this (because it's based solely on the declared type, not the syntactic context.)

carljm avatar Dec 18 '25 23:12 carljm