Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mypy local stubs

Tags:

python

mypy

I am trying the typing hint introduced by Python 3.5 and got a problem by using local stubs as the typing hint with mypy.

The experiment I do is to creat kk.py containing

def type_check(a):
    pass

Also, I put kk.pyi containing

def type_check(a: int):...

in the same directory. In this way, I tried to trigger the error of "ncompatible types in assignment" by passing a string to type_check in kk.py. However, when I ran mypy kk.py and get no error.

Thus I tried another way that mypy doc suggests, which is to set environment variable MYPYPATH to ~/some/path/stub and put kk.pyi in the directory. I got the same error, however.

Anyone can help me on this?

Here is the mypy wiki on how to use a local stub.

like image 853
Musen Avatar asked May 31 '16 05:05

Musen


1 Answers

I do not know why someone have voted down this question without answering it or commenting about why he/she disliked it, but here is the answer I figured out:

The stub file of mypy only works when importing a module. Thus, if you have

def try_check(a):
    pass

in kk.py, and

def try_check(a: int):...

in kk.pyi in the same directory with kk.py or in the directory that the MYPYPATH specifies, mypy will type check the python file if you import kk. It is, if you have

import .kk
kk.try_check('str')

in test.py and run mypy test.py, mypy will report the type conflict. However, it will not report the conflict if you have

try_check('str')

in kk.py.

You can type check functions in the program that contains the function definition If you write the typing hint explicitly in the definition of the function. For instance, you can write

def try_check(a: int):
    pass

try_check('str')

in kk.py and then mypy kk.py. Mypy will report the type conflict.

like image 114
Musen Avatar answered Sep 20 '22 09:09

Musen