some problems for an introductory python test

Chris Angelico rosuav at gmail.com
Wed Aug 11 17:36:09 EDT 2021


On Thu, Aug 12, 2021 at 7:25 AM Rob Cliffe via Python-list
<python-list at python.org> wrote:
>
> On 11/08/2021 19:10, MRAB wrote:
> > On 2021-08-11 18:10, Wolfram Hinderer via Python-list wrote:
> >>
> >>
> >> Am 11.08.2021 um 05:22 schrieb Terry Reedy:
> >>> Python is a little looser about whitespace than one might expect
> >>> from reading 'normal' code when the result is unambiguous in that it
> >>> cannot really mean anything other than what it does.  Two other
> >>> examples:
> >>>
> >>> >>> if3: print('yes!')
> >>> yes!
> >>> >>> [0]  [0]
> >>> 0
> >>
> >> Not sure what you mean here - is it a joke? The first looks like an if
> >> statement, but isn't. The missing space *does* make a difference. (Try
> >> "if0" instead.)
> >>
> > I see what you mean. It's a type annotation:
> >
> >     var: type
> >
> > where the "type" is a print statement!
> >
> >> The second is normal indexing, which allows white space. I wouldn't
> >> consider that surprising, but maybe I should? (Honest question, I really
> >> don't know.)
> >>
> I looked at the if3 example, and I was gobsmacked.  I momentarily
> assumed that "if3" was parsed as "if 3", although that clearly makes no
> sense ("if3" is a valid identifier).
> Then I saw the "if0" example and I was even more gobsmacked, because it
> showed that my assumption was wrong.
> I've never used type annotations, I've never planned to used them. And
> now that all is revealed, I'm afraid that my reaction is: I'm even more
> inclined never to use them, because these examples are (to me) so confusing.

Don't judge a feature based on its weirdest example. Based on this
example, you should avoid ever using the len() built-in function:

>>> def show_count(n, word):
...     return "{{}} {{:{0}.{0}}}".format(len(word)-(n==1)).format(n, word)
...
>>> show_count(0, "things")
'0 things'
>>> show_count(1, "things")
'1 thing'
>>> show_count(5, "things")
'5 things'
>>> show_count(2, "widgets")
'2 widgets'
>>> show_count(1, "widgets")
'1 widget'

Any syntax can be abused. And the same thing would happen in any other
context. The only difference is that, in a declaration like "if3:
print()", the name if3 doesn't have to have been assigned already,
avoiding this problem:

>>> {
...     if3: print("Hello")
... }
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'if3' is not defined

ChrisA


More information about the Python-list mailing list