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

Nick Coghlan ncoghlan at gmail.com
Wed Aug 3 11:24:45 EDT 2016


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.".

I'd be much happier if we made initialisation mandatory, so the above
would need to be written as either:

    a: float = 0.0 # Or other suitable default value

or:

    a: Optional[float] = None

The nebulous concept (and runtime loophole) where you can see:

    class Example:
        a: float
        ...

but still have Example().a throw AttributeError would also be gone.

(Presumably this approach would also simplify typechecking inside
__new__ and __init__ implementations, as the attribute will reliably
be defined the moment the instance is created, even if it hasn't been
set to an appropriate value yet)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list