some problems for an introductory python test

Cameron Simpson cs at cskk.id.au
Thu Aug 12 19:42:20 EDT 2021


On 11Aug2021 09:11, Hope Rouselle <hrouselle at jevedi.com> wrote:
>Greg Ewing <greg.ewing at canterbury.ac.nz> writes:
>> That may not be doing what you think it's doing. Consider also
>>
>>>>> if0: print('yes!')
>> yes!
>
>So, yes, that's puzzling.
>
>>>> 0 == False
>True
>>>> if0: print("yes")
>yes
>>>> if(0): print("yes")
>
>>>>
>
>What's going on there?

1: "if0" does not mean "if 0"; "if0" is a valid identifier. Like "x0", "x1".

2: It took me a while to see, but this is a type annotiation.

This line:

    if0: print('yes!')

says that the name "if0" should contain a value described by the return 
value of the expression "print('yes!')". Like this:

    label : str

says that we expect a string in the variable "label".

Remember that Python is strongly typed, but variables may reference 
objects of any type. Type annotations are optional things reflecting 
that in practice most variables are expected to reference specific 
types. This lets is run static linters against programmes to catch 
mistakes exposed by the type descriptions.

Also, type annotations have _no_ runtime effect. So if that expression 
returns an invalid type description, nobody cares!

However, if you hand this code to a type aware linter such as mypy you 
might get bitter complaints about nonsense. (Or, since print() returns 
None, no complaint - it just means you expect this variable to hold the 
value None. You'd get complaints about unused variables etc.)

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list