PEP 484 stubs with generic types
Ian Kelly
ian.g.kelly at gmail.com
Tue Nov 17 12:49:00 EST 2015
Playing around a bit with PEP 484, I annotated a function that returns
an asyncio.Future:
import asyncio
def get_future() -> asyncio.Future[int]:
future = asyncio.Future()
future.set_result(42)
return future
The problem with this is that in Python 3.5, asyncio.Future can't be
used as a generic type. Fortunately, the typeshed repository provides
a stub that defines it as a generic type:
https://github.com/python/typeshed/blob/master/stdlib/3.4/asyncio/futures.pyi
This is fine for running a static type checker, but it still creates a
problem when actually running the code. The real asyncio.Future
doesn't support indexing, and so the annotation causes a TypeError at
runtime.
I could write the annotation as a forward reference, avoiding the TypeError:
def get_future() -> "asyncio.Future[int]":
...
But PEP 484 stipulates that a forward reference "should evaluate
without errors once the module has been fully loaded", so this is
invalid.
Is there any advice for this case? How are generic types meant to be
used with stub files?
More information about the Python-list
mailing list