python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.55k stars 2.84k forks source link

Inconsistent error when aliasing a type from a module without stubs #2801

Open frankpf opened 7 years ago

frankpf commented 7 years ago

test_mypy.py:

import pymongo # this can be any third-party module without stubs

Collection = pymongo.collection.Collection

def func(a: Collection) -> bool:
   return True

Here's the output of mypy test_mypy.py :

test_mypy.py:1: error: No library stub file for module 'pymongo'
test_mypy.py:1: note: (Stub files are from https://github.com/python/typeshed)
test_mypy.py: note: In function "func":
test_mypy.py:5: error: Invalid type "test_mypy.Collection"

However, if I change test_mypy.py to this:

import pymongo

def func(a: pymongo.collection.Collection) -> bool:
  return True

then mypy does not complain about pymongo.collection.Collection being an invalid type. This seems inconsistent/wrong, Collection is not an invalid type, it's just an alias for a type without a stub.

frankpf commented 7 years ago

This seems similar to https://github.com/python/mypy/issues/2075.

gvanrossum commented 7 years ago

Looks like it doesn't treat Collection = pymongo.collection.Collection as a type alias definition? In the second example, pymongo is an object of type Any and attributes thereof are also treated as Any.

Agreed this should be dealt with better.

JukkaL commented 5 years ago

I've hit this issue as well. It's not clear if Collection should be treated as a type alias, since it could also be an ordinary variable. Mypy should perhaps behave as if there was an explicit Any annotation. This doesn't generate an error:

...
Collection: Any = pymongo.collection.Collection  # Note type annotation!

def func(a: Collection) -> bool:  # OK
   return True