Sprotty
Sprotty

Reputation: 5973

Python Type Hints ignored

I'm new to python and experimenting with type hints, however they only seem to work in some instances. They seem to work as expected on the property return type, however when I try to assign an integer to a string value (i.e. self._my_string = 4), I get no issues reported.

class TypeHintTest(object):
    _my_string: str

    def __init__(self):
        self._my_string = 4  # no error

    @property
    def as_int(self) -> int:  
        return self._my_string  # Error : expected int got str

The resulting object then contains an int value (as expected).

I'm using pyCharm 2018.3.2 Community edition, the interpreter is 3.6

enter image description here

The following question seems to be similar, but the solution of changing the constructor to def __init__(self) -> None does not change anything. Python: All type hints errors in subclass constructure seems ignored

Upvotes: 2

Views: 2648

Answers (3)

vv2006-mc
vv2006-mc

Reputation: 107

for enforcing type hints, there is a module called beartype it can enforce type hints for the whole package or just the function, etc...

basically

from bear type import beartype

@beartype
def func(a:str):   #beartype raises BeartypeCallHintParamViolation if a is not str
    #logic

for more information visit the docs

Upvotes: 0

Sprotty
Sprotty

Reputation: 5973

As @FHTMitchell points out its a bug in PyCharm

see Bug tracker entry

Upvotes: 2

user8181134
user8181134

Reputation: 486

Type hints are, as the name suggests, hints. Python does not raise an error if you assign a different type to a variable.
Pycharm, however, should say that it expected another variable type.

Upvotes: 3

Related Questions