microsoft / pyright

Static Type Checker for Python
Other
13.32k stars 1.45k forks source link

Pyright: Cannot assign to attribute for class "Block*" #8795

Closed GianmarcoAndreana closed 2 months ago

GianmarcoAndreana commented 2 months ago

Note: if you are reporting a wrong signature of a function or a class in the standard library, then the typeshed tracker is better suited for this report: https://github.com/python/typeshed/issues.

If you have a question about typing or a behavior that you’re seeing in Pyright (as opposed to a bug report or enhancement request), consider posting to the Pyright discussion forum.

Describe the bug When using pyright in conjunction with Pyomo (6.8.0), Pyright is reporting that it cannot assign to an attribute "x" for class "Block*". This issue have appeared since Pyright 1.1.374 release. Before Pyright was correctly operating and not reporting these warnings.

Code or Screenshots


import pyomo.environ as pyo
model = pyo.ConcreteModel()
model.x = pyo.Var(within=pyo.Reals)
screen

VS Code extension or command-line I'm using Neovim 0.11.0 (LazyVim) with Pyright 1.1.377.

erictraut commented 2 months ago

Pyright is working as intended here, so I don't consider this a bug.

The pyomo library appears to have a few type annotations, but it is mostly untyped. It also doesn't have any "py.typed" marker file, which means that its authors don't make any claims about it being typed. I presume that you have not installed (or locally created) type stubs for the library. That means pyright will do its best to infer missing information from the library's source code.

I don't know anything about pyomo or its interface, but looking at its source, there is no attribute x defined in the Block class or its base classes. I also don't see a __setattr__ method.

Is there a particular reason why you think that you should be able to assign a value to an attribute named x without a type checker generating a type violation?

Here are a few options:

  1. In your pyright configuration, set useLibraryCodeForTypes to false. This tells pyright to treat all symbols imported from untyped libraries as Unknown. You will lose all type checking and language server features (completions, etc.) for these libraries, but it will eliminate the type checking errors.
  2. Find type stubs for pyomo or create your own partial stubs for the portions of the library that you consume.

I'm closing the issue because there doesn't appear to be anything actionable with regard to pyright.

GianmarcoAndreana commented 2 months ago

Thank you for the clear explanation. I solved my problem following your first suggestion.