Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A type created with type(...) is not valid as a type #8897

Closed
mehaase opened this issue May 26, 2020 · 6 comments
Closed

A type created with type(...) is not valid as a type #8897

mehaase opened this issue May 26, 2020 · 6 comments

Comments

@mehaase
Copy link

mehaase commented May 26, 2020

Note: I tried searching for related issues but the search keyword type obviously has a lot of hits in this repo with a different meaning. Apologies if this has been asked before.

It seems that types created using type(...) are not valid as type annotations.

MyType = type("MyType", (dict,), {})
x: MyType = MyType()


class MyOtherType:
    pass
y: MyOtherType = MyOtherType()

The result is:

> mypy example/test.py
example/test.py:2: error: Variable "example.test.MyType" is not valid as a type
example/test.py:2: note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases
Found 1 error in 1 file (checked 1 source file)

Is this considered a bug or an intentional design decision? Is there a way to use this kind of type as a type annotation?

Python 3.7.5, MyPy 0.770.

@JelleZijlstra
Copy link
Member

This is generally too dynamic for mypy to understand. It would probably be quite difficult to make it work in mypy except in simple cases where all the arguments are static.

@g-braeunlich
Copy link

g-braeunlich commented Aug 5, 2020

What about the following?

class X: pass

x: X # works

Y = cast(type, X)
y: Y # is not valid as a type

Z: type = X
z: Z # is not valid as a type

It would be cool to have at least one way to tell mypy that some object is actually a type, e.g. X: typing.Type[str] = type("X", (str,), {})

@gvanrossum
Copy link
Member

But then using that object in an annotation is useless. You could just as well say ‘z: object’.

@g-braeunlich
Copy link

Also in my example X: typing.Type[str] = type("X", (str,), {}) ?
Would not x: X indicate x: str (or subtype of str)?

@gvanrossum
Copy link
Member

Mypy doesn’t special-case calls to type() that way. To me this feels like something too dynamic to expect mypy to understand, sorry. And IIRC Type[str] has a different meaning (the type of ‘str’?).

@jenstroeger
Copy link

For visitors of this issue, there’s another related discussion here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants