0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Or alternatively, the --disallow-untyped-defs flag, if you prefer fixing functions missing type hints immediately. Also, it's probably worth noting that the reason this function/the function in the question are considered untyped is because they're both completely missing in type hints -- you'd need to add in the missing return type hint of -> None. (Not sure if OP knew this, or just forgot.)
@Michael0x2a have expanded my answer... just noticed that you've answered very similar questions quite a few times now!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.