python-3.xcsvmypytypeshed

mypy (typeshed) rejects csv.excel as a possible value for the return of csv.Sniffer.sniff


Using mypy to statically check some of my code and got this problem. Code example:

import csv

d: csv.Dialect = csv.excel
d = csv.Sniffer().sniff("a")

but mypy gives this error in the first assignment to d:

error: Incompatible types in assignment (expression has type "Type[excel]", variable has type "Dialect")

So the natural fix for this is to change the type of the variable.

from typing import Type

import csv

d: Type[csv.Dialect] = csv.excel
d = csv.Sniffer().sniff("a")

But now I get this error on the second assignment to d:

error: Incompatible types in assignment (expression has type "Dialect", variable has type "Type[Dialect]")

But this is odd because csv.excel is a valid return for the sniff function so surely they must have the same type.

Python 3.7.3, mypy 0.701


Solution

  • I think this is a bug in the typeshed: I've raised an issue

    According to typeshed, Sniffer.sniff returns a value of type csv.Dialect whereas in fact it returns a value of type Type[csv.Dialect]