Krish Mahajan
Krish Mahajan

Reputation: 263

Class instance type checking mypy python

I have following two classes in two different python Modules

class Node(object):

    def __init__(self, data: int) -> None:
        if data is not None:
            self._index: int = data

    def get_node_index(self) -> int:
        if self._index is not None:
            return self._index

AND

from Graph import Node


class NodeTest(object):
    def func(self):
        n = Node(4)
        print(n.get_node_index())
        data: bool = n.get_node_index()
        print(type(data))


if __name__ == '__main__':
    a = A()
    a.func()

I get the following output when i run main in second class

4
<class 'int'>

I can't understand why mypy is not warning that type of data has to be int if i'm assigning it using n.get_node_index() which has a return type of int

Upvotes: 0

Views: 650

Answers (1)

Sam Mason
Sam Mason

Reputation: 16184

I think you want to pass --check-untyped-defs to mypy

for example, the following doesn't give any errors by default:

def foo():
  a = 5
  b: bool = a

but when run as mypy --check-untyped-defs foo.py I get:

Incompatible types in assignment (expression has type "int", variable has type "bool")

as @Michael0x2a pointed out you can also pass --disallow-untyped-defs to mypy which will cause it to complain that your NodeTest.func is untyped and hence it won't be checked. You'd then want to annotate it to be:

    def func(self) -> None:

allowing it to be type-checked.

Upvotes: 2

Related Questions