[Python-ideas] Lessons from typing hinting Whoosh (PEP484)

Andrew Barnert abarnert at yahoo.com
Mon Nov 16 12:19:14 EST 2015


On Nov 15, 2015, at 22:17, Matt Chaput <matt at whoosh.ca> wrote:
> 
> 2. It would be really nice if we could have "type aliasing" (or whatever it's called). I have a lot of types that are just something like "Tuple[int, int]", so type checking doesn't help much. It would be much more useful if I have a value that Python sees as (e.g.) an int, but have the type system track it as something more specific. Something like this:
> 
>    DocId = typing.TypeAlias(int)
>    DocLength = typing.TypeAlias(int)
> 
>    def id_and_length() -> Tuple[DocId, Length]:
>        docid = 5  # type: DocId
>        length = 10  # type: Length
>        return docid, length

It sounds like you want a subtype that adds no new semantics or other runtime effects. Like this:

    class DocId(int): pass
    class DocLength(int): pass

    def id_and_length() -> Tuple[DocId, DocLength]:
        return DocId(5), DocLength(10)

These will behave exactly like int objects, except that you can (dynamically or statically) type check them. It does mean that if someone uses "type(spam[0]) == int" it will fail, but I think if you care either way, you'd actually want it to fail. Meanwhile, "isinstance(spam[0], int)" or "spam[0] + eggs" or even using it in a function that requires something usable as a C long will work as expected. The object will also be the same size as an int in memory (although it will pickle a little bigger). It can't be optimized into a constant at compile time, but I doubt that's ever an issue. And it makes your intentions perfectly clear.


More information about the Python-ideas mailing list