[Python-ideas] Trial balloon: adding variable type declarations in support of PEP 484

Steven D'Aprano steve at pearwood.info
Wed Aug 3 13:35:32 EDT 2016


On Wed, Aug 03, 2016 at 09:11:42AM -0700, Guido van Rossum wrote:
> On Wed, Aug 3, 2016 at 8:24 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> > On 3 August 2016 at 10:48, Alvaro Caceres via Python-ideas
> > <python-ideas at python.org> wrote:
> >> The criticism I would make about allowing variables without assignments like
> >>
> >>   a: float
> >>
> >> is that it makes my mental model of a variable a little bit more complicated
> >> than it is currently. If I see "a" again a few lines below, it can either be
> >> pointing to some object or be un-initialized. Maybe the benefits are worth
> >> it, but I don't really see it, and I wanted to point out this "cost".
> >
> > This concern rings true for me as well - "I'm going to be defining a
> > variable named 'a' later and it will be a float" isn't a concept
> > Python has had before. I *have* that concept in my mental model of
> > C/C++, but trying to activate for Python has my brain going "Wut?
> > No.".
> 
> Have you annotated a large code base yet? This half of the proposal
> comes from over six months of experience annotating large amounts of
> code (Dropbox code and mypy itself).
[...]
> IOW I want to be able to write this code as
> 
>         result: Type
>         if op == 'not':
>             self.check_usable_type(operand_type, e)
>             result = self.chk.bool_type()
>         elif op == '-':
>         # etc.

Just playing Devil's Advocate here, could you use a type hint *comment*?

    #type result: Type
    if op == 'not':
        self.check_usable_type(operand_type, e)
        result = self.chk.bool_type()
    elif op == '-':
        # etc.

Advantages: 

- absolutely no runtime cost, not even to evaluate and discard the name 
following the colon;
- doesn't (wrongly) imply that the name "result" exists yet;

Disadvantages:

- can't build a runtime __annotations__ dict;


[...]
> But, again, real problems arise when the type of an *initialized*
> instance must always be some data structure (and not None), but you
> can't come up with a reasonable default initializer that has the
> proper type.

Again, playing Devil's Advocate... maybe we want a concept of 
"undefined" like in Javascipt.

    result: Type = undef

which would make it clear that this is a type declaration, and that 
result is still undefined.

Disadvantages:

- Javascript programmers will think you can write `print(result)` and 
get "undef" (or similar);
- requires a new keyword.


-- 
Steve


More information about the Python-ideas mailing list