[Python-ideas] PEP 484 (Type Hints) -- first draft round

Cem Karan cfkaran2 at gmail.com
Sun Jan 18 03:09:01 CET 2015

On Jan 16, 2015, at 9:11 PM, Guido van Rossum <guido at python.org> wrote:

> On Fri, Jan 16, 2015 at 5:57 PM, Cem Karan <cfkaran2 at gmail.com> wrote:
>> If we're using decorators for the annotations, why not use them for the typing as well?
> Because annotations were intended for type hints.
>> E.g.,
>> @typing.type(a, int)
>> @doc.doc(a, "some doc")
>> def f(a):
>>     pass
>> This would be the equivalent of:
>> def f(a: {"typing.type": int, "doc.doc": "some doc"}):
>>     pass
>> The whole dictionary idea will be hidden, and annotations can be used for other purposes while still supporting typing information.  I'll admit that stacking the decorators means the code could get very deep, but it still feels like the least bad thing to do.
> You're taking this "nobody should be more equal than others" thing too far. :-) We're trying to come up with a standard way of doing one very important thing.

I understand what you're saying, but I feel like annotations have the capability to be MUCH more useful than just as a place to hold type hints.  My example is fairly small, but it feels cleaner than some of the other solutions (e.g., Sphinx's :param: & :type: statements, see http://sphinx-doc.org/domains.html#info-field-lists).  I just don't want to close the door to other uses, which is what will happen; as others have said, if type hinting becomes the officially blessed use for annotations, then other uses will be effectively deprecated, even if it is technically possible to continue using them for other purposes.  

Here is another way (this is a hack and requires more thought):

# In the typing library
class Type(object):
    def __init__(self, t):
        self._t = t
    def t(self):
        return self._t
# End of class Type

# In use:
def foo(a: Type(int)):

I haven't thought too much more about it, but I'm sure someone else can come up with a better way of doing it.  The basic idea is that the name of the class and the fact that the argument is the type in question is always known; a static analyzer can scan for it fairly easily.  If the type of the annotation is not Type, then you know something else is going on, and the analyzer can skip it.  This avoids the question of 'is this dict the type, or is there something inside of it that also includes the type?'

This can be further extended using decorators that generate dynamic checking code in debug mode, and are no-ops in normal mode (accessible by a command-line switch or something).

I'm not sure at them moment how to handle having both Type objects and other information.  I suspect having a catch-all *args, **kwargs in the init is going to be the least bad solution, but other ideas are welcome!

Cem Karan

More information about the Python-ideas mailing list