Unexpected Type Hint Warnings

I have a python project that I originally setup with a venv using python 3.12. I recently had to switch it to a venv using 3.11. After making the switch I have been seeing a lot of unexpected type hint warnings that I was not seeing before.

For example:

response_path = pathlib.Path("path/to/my/file")
with open(str(response_path), 'wb') as fp:
    pickle.dump(response, fp)  # WARNING: Expected type 
                               #'SupportsWrite[bytes]', got 
                               # 'BinaryIO' instead 
...
for i, box_1 in enumerate(boxes):
    for j in range(i + 1, len(boxes)):  # WARNING: Expected type 
                                        #'SupportsIndex', got 'int' 
                                        # instead
...
events: list[Event] = []
# Add some Event objects to the list
some_event = events[0].my_attribute # WARNING: Unexpected type(s): (int) 
                                    # Possible type(s): (SupportsIndex) 
                                    # (slice)

I have tried Invalidate Caches…, Repair IDE, and Restore Default Settings, but none of those resolve the issue. However, the warnings disappear if I revert back the 3.12 venv.

9

There are similar problems for me, and when I write a project, even though all the items are entered correctly, it gives an error warning under some words.

1

I should note that I also recently updated to Build #PY-242.22855.92. Even after reverting back to python 3.12 I am still seeing some of the problematic warnings. Specifically the file pointer warning about SupportsWrite[bytes].

Switching back to Build #PY-242.21829.153 appears to have fixed many/most of the issues.

2

got the same issue on Intellij idea 2024.2.2 when indexing list by an integer…

# Unexpected type(s): (int) Possible type(s): (SupportsIndex) (slice) 

1

I prefer to use the previous version for now, this bug caused a big loss in our collection.

I don't understand why the programmers need to update it when Pycharm is working well.

You also gave us a habit that we cannot work with any other similar idea. Those who use it regularly will understand what I'm talking about.

1
# Write the JSON payload to the file, explicitly specifying encoding
with open(file_path, 'w', encoding='utf-8') as out_data:
    json.dump(payload, out_data, indent=4, sort_keys=True)

PyCharm 2024.2.2 (Professional Edition)
Build #PY-242.22855.92, built on September 19, 2024

out_data in the json.dump throws the following warning:

Expected type 'SupportsWrite[str]', got 'TextIO' instead
3

I am really sorry for such an uncommitted team that we are involved in the irresponsibility of these unprofessional people. After all these days, the problem is still not fixed, it is better to use the free versions of similar companies.

-2

should work for JetBrains IDEs

if typing.TYPE_CHECKING:
    from _typeshed import SupportsWrite
    file: SupportsWrite[str]

with open(file_path, "w") as file:
    json.dump(obj=data, fp=file, indent=4)

1

Same problem having warning “Expected type 'SupportsWrite[str]', got 'TextIO' instead”. 

https://www.devgem.io/posts/resolving-pycharm-type-hint-warning-for-pickle-dump-method suggests using Pycharm Inspection Comments which works for me

# noinspection PyTypeChecker
0

(came here via a Google search…)

I just got bitten by this too, with this simple code fragment:

column_names = [chr(i + ord('A') - 1) for i in range(1, len(title_list) + 1, 1)]
last_col: str = column_names[-1]

PyCharm 2024.3 Build #PY-243.21565.199 says that every item in the range call is wrong (it expects SupportsIndex rather than int apparently), and it's the same story with the “-1” in the next line.

Looks to me that the type checker is broken, so how do I/we report that?

In the meantime I'm doing the same as “Spel” suggested above and suppressing the check where it's getting it wrong - but I really don't like to have to do that, type check is useful (usually)

1

Still the same in the fresh PyCharm

0

Hi! This issue requires thorough investigation, please create an issue on YouTrack, attach all relevant information for quicker resolution.

0

I have the same problem(pycharm pro 2024.3.6, python 3.11.9). After a brief investigation, I found that it should be related to the following two parts:

JetBrains\Toolbox\PyCharm Professional\plugins\python-ce\helpers\typeshed\stdlib\builtins.pyi 

@final
class range(Sequence[int]):
    @property
    def start(self) -> int: ...
    @property
    def stop(self) -> int: ...
    @property
    def step(self) -> int: ...
    @overload
    def __new__(cls, __stop: SupportsIndex) -> Self: ...
    @overload
    def __new__(cls, __start: SupportsIndex, __stop: SupportsIndex, __step: SupportsIndex = ...) -> Self: ...

and typing_extensionspackage(version = 4.12.2)

venv\Lib\site-packages\typing_extensions.py

if sys.version_info >= (3, 12):
    SupportsInt = typing.SupportsInt
    SupportsFloat = typing.SupportsFloat
    SupportsComplex = typing.SupportsComplex
    SupportsBytes = typing.SupportsBytes
    SupportsIndex = typing.SupportsIndex
    SupportsAbs = typing.SupportsAbs
    SupportsRound = typing.SupportsRound
else:
	...
    @runtime_checkable
    class SupportsIndex(Protocol):
        __slots__ = ()

        @abc.abstractmethod
        def __index__(self) -> int:
            pass

 

but in JetBrains\PyCharm2024.3\python_stubs\1616765353\builtins.py, the ‘range’ class is defined as:

class range(object):
    """
    range(stop) -> range object
    range(start, stop[, step]) -> range object
    
    Return an object that produces a sequence of integers from start (inclusive)
    to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
    start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
    These are exactly the valid indices for a list of 4 elements.
    When step is given, it specifies the increment (or decrement).
    """
    def count(self, value): # real signature unknown; restored from __doc__
        """ rangeobject.count(value) -> integer -- return number of occurrences of value """
        return 0

    def index(self, value): # real signature unknown; restored from __doc__
        """
        rangeobject.index(value) -> integer -- return index of value.
        Raise ValueError if the value is not present.
        """
        return 0

    def __bool__(self, *args, **kwargs): # real signature unknown
        """ True if self else False """
        pass

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, *args, **kwargs): # real signature unknown
        """ Return self[key]. """
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass

    def __init__(self, stop): # real signature unknown; restored from __doc__
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass
            

 

I can't figure out how PyCharm's syntax checking and code navigation work, because in the same file, some uses of 'range' don't have such problem.

...         

0

It's possible your case is a false positive. Please create a new bug report with the steps to reproduce it on YouTrack

Make sure to check on the 2025.2.0.1 version

0

请先登录再写评论。