Monday, 14 October 2019

Store and assert type in a Python class

PyCharm CE 2019.2.3 warns me about a class in that I store a list of data along with the value data type. I have tried to reduce it to the essence:

class Data:
    def __init__(self, length, data_type):
        assert isinstance(length, int) and length >= 0
        assert isinstance(data_type, type)  # commenting this line out removes the warning
        self._data = [None] * length
        self._data_type = data_type

    def set_field(self, index, value):
        assert isinstance(value, self._data_type)  # commenting this line out removes the warning
        assert isinstance(index, int)
        self._data[index] = value

I get a warning on the index:

enter image description here

Unexpected type(s):
(int, type)

Possible types:
(int, None)
(slice, Iterable[None])

Inspection Info: This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotation.

Further comments:

  • removing at least one of the two marked assertions removes the warning

  • it is rather confusing that the warning appears for the index while those asserts refer to the value

  • adding additional asserts or type-hinting docstrings did not remove the warning for me

My question: Am I doing something wrong with this storing and asserting of types? Is there any reason for that warning, and if not, do you see a convenient way to remove it?



from Store and assert type in a Python class

No comments:

Post a Comment