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

Nick Coghlan ncoghlan at gmail.com
Fri Aug 5 03:27:20 EDT 2016


On 4 August 2016 at 23:29, Steven D'Aprano <steve at pearwood.info> wrote:
> On Thu, Aug 04, 2016 at 10:37:33PM +1000, Nick Coghlan wrote:
>> Otherwise we're at risk of allowing thoroughly confusing runtime behaviour like:
>>
>>     >>> a = "Not an int"
>>     >>> def f():
>>     ...     # a: int would go here
>>     ...     print(a) # This should really fail
>>     ...
>>     >>> f()
>>     Not an int
>
> I would expect that the type-checker will complain that you're declaring
> a local variable "a" but there's no local "a" in the function. If the
> checker isn't that smart, I expect it would complain that "a" is set to
> a string, but declared as an int. Either way, the type-checker ought to
> complain.

Guido's reply clarified that he expects the compiler to be declaration
aware (so it correctly adds "a" to the local symbol table when a type
declaration is given), which means functions will be free of ambiguous
behaviour - they'll throw UnboundLocalError if a name is declared and
then referenced without first being defined.

That means it's mainly in classes that oddities will still be possible:

>>> a = "Not an int"
>>> class Example:
...     # a: int
...     # a class: int
...     other_attr = derived_from(a) # Oops
...     a = 1
...

That's probably acceptable to handle as "Don't do that" though, and
leave it to typecheckers to pick it up as problematic "Referenced
before definition" behaviour.

Regards,
Nick.

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


More information about the Python-ideas mailing list