Replies: 2 comments
-
Parameterized type variables are not currently supported in the Python type system. You cannot use a generic type as a bound for a TypeVar. (Mypy doesn't currently emit an error if a generic type is used in a bound, but it should.) A parameterized TypeVar is known as a "higher-kinded type" (HKT). There have been some discussions about introducing HKTs into the Python type system, but these discussions haven't yet led to any concrete proposals. The Here's a solution that works with the current version of mypy. You can use an explicit specialization when calling the c = Connection[Any].connect() |
Beta Was this translation helpful? Give feedback.
-
This question is now 2Y old and the code illustrated is quite out of date compared to the state of the Python typing system. Closing it in favour of: |
Beta Was this translation helpful? Give feedback.
-
Hello,
Psycopg objects are parametrized with a
Row
type, which is the type of object returned by thefetch*()
methods. Normally it isTupleRow = Tuple[Any, ...]
, but it can be customized using arow_factory
argument to the constructor methodConnection.connect()
. For instance, in order to return dicts instead of tuples, one can useConnection.connect(..., row_factory=dict_row)
. At the moment, theconnect()
signature, simplified, is:Because now we need to subclass
Connection
, I would like to annotateconnect()
using a parametric Self and avoid the need to redeclare all of the above in each subclass (yes, I am aware of PEP 673, but I'm trying to make this work with the current mypy implementation).I don't seem able to declare correctly the default
TupleRow
together with a parametric self. The current implementation I have attempted is, in a self-contained example:With this implementation,
connect()
with no argument is reported by mypy 0.950 as needing annotation and of typeConnection[Any]
:One way I wish it was possible to implement this would be with a parametrized self, aka returning
_Self[Row]
in the first variant and_Self[TupleRow]
in the second. It doesn't seem possible because error: Type variable "_Self" used with arguments, which is legit. I have then tried to leave_Self
generic, by defining it as_Self = TypeVar("_Self", bound="Connection")
, but this gives fails with error: Missing type parameters for generic type "Connection".An alternative attempt, which I think would be even better than using
@overload
, would be if the default value forrow_factory
was able to give information about the parameter type. However it doesn't seem to work either:In this test, the row_factory default is also reported to be incompatible with the parameter type.
cno
, again, has parameter typeAny
:My questions:
Thank you very much!
P.S. Original issue at psycopg/psycopg#308
Beta Was this translation helpful? Give feedback.
All reactions