Create a class which wraps the cursor, type-hinting the specific cursor type you wish to use.
(Type hinting any BaseCursor subclass results in the error):
from typing import Callable
from pyathena.cursor import Cursor
class MyDbWrapperClass:
database_cursor: Callable[[], Cursor]
def __init__(self, database_cursor: Callable[[], Cursor] )
self.database_cursor = database_cursor
my_db_wrapper_instance = MyDbWrapperClass(database_cursor=lambda: Connection(
work_group=s.ATHENA_WORKGROUP,
region_name=s.ATHENA_REGION,
cursor_class=Cursor,
).cursor())
Run mypy on the given file
mypy .
Result:
my-repo/my-file:linenumber error: Argument "database_cursor" to "MyDbWrapperClass" has incompatible type "Callable[[], BaseCursor]"; expected "Callable[[], Cursor]" [arg-type]
Cause of error
BaseCursor is type hinted as the return value of the Connection.cursor method in ``
Though every instance of a subclass of BaseCursor is an instance of BaseCursor, as an abstract class, BaseCursor isn't instantiable, and if it were, a concrete instance of the BaseCursor could not be used in place of any of the subclasses.
Proposed Solution
Replace BaseCursor with a CursorType TypeVar, which is bound to BaseCursor
Minimal Example to recreate:
Create a class which wraps the cursor, type-hinting the specific cursor type you wish to use.
(Type hinting any BaseCursor subclass results in the error):
Run mypy on the given file
Result:
Cause of error
BaseCursor
is type hinted as the return value of the Connection.cursor method in ``Though every instance of a subclass of
BaseCursor
is an instance of BaseCursor, as an abstract class, BaseCursor isn't instantiable, and if it were, a concrete instance of the BaseCursor could not be used in place of any of the subclasses.Proposed Solution
Replace
BaseCursor
with a CursorTypeTypeVar
, which is bound toBaseCursor
Define the TypeVar
Replace BaseCursor with the type var in the type signature for
Connection.cursor
method and the type hint for the constructor'scursor_class
argumentEDIT:
It appears the solution isn't as straightforward as I thought. Digging in further....