Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #98939 > unrolled thread

PEP 484 stubs with generic types

Started byIan Kelly <ian.g.kelly@gmail.com>
First post2015-11-17 10:49 -0700
Last post2015-11-17 10:49 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python


Contents

  PEP 484 stubs with generic types Ian Kelly <ian.g.kelly@gmail.com> - 2015-11-17 10:49 -0700

#98939 — PEP 484 stubs with generic types

FromIan Kelly <ian.g.kelly@gmail.com>
Date2015-11-17 10:49 -0700
SubjectPEP 484 stubs with generic types
Message-ID<mailman.400.1447782587.16136.python-list@python.org>
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?

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web