Issue
This program:
class Array:
def __init__(self, underlying):
self.underlying = underlying
def __class_getitem__(cls, key):
return Array(key)
def __getitem__(self, key):
pass
def __str__(self):
return f"Array({self.underlying=})"
def foo(name, kind):
pass
foo(name="x", kind=Array["int"])
is flagged by mypy
:
x.py:17: error: The type "Type[Array]" is not generic and not indexable [misc]
The __getitem__
is something I added just to see if it would resolve the issue (it did not). I'm not intending to use Array
here as a type (in the typing
sense), just for cute syntax to pass an array type somewhere else.
What does this mypy
error mean and how can I fix it (preferably with something other than # ignore
comments)?
Solution
I'm not intending to use
Array
here as a type (in thetyping
sense), just for cute syntax to pass an array type somewhere else.
__class_getitem__
is only for typing. See docs:
classmethod
object.__class_getitem__(cls, key)
Return an object representing the specialization of a generic class by type arguments found in key.
And more specifically:
Using
__class_getitem__()
on any class for purposes other than type hinting is discouraged.
So unfortunately, it looks like what you want is not possible. Just use the regular constructor syntax, Array("int")
.
Also, just in case you weren't aware, special methods shouldn't be used in unintended ways:
Any use of
__*__
names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.
Answered By - wjandrea
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.