I read PEP 614 (Relaxing Grammar Restrictions On Decorators)

The other day, PEP 614 (Relaxing Grammar Restrictions On Decorators) became Final Commit I saw / python / peps / pull / 1437). So, this time I will read PEP 614.

Overview

  buttons = [QPushButton(f'Button {i}') for i in range(10)]

  @buttons[0].clicked.connect  # => NG
  def spam():
      ...

approach

The grammar so far

decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE

It was

decorator: '@' namedexpr_test NEWLINE

Changed to. that's all.

It's hard to understand that. namedexpr_test is a grammatical element that points to a Python expression. The following are the expressions (from 6. Expressions — Python 3.8.3 Documentation):

There are various things. These are now available for decorators. Please note that some definitions may not be available (such as await).

Example

Try using a lambda expression as a decorator ...

>>> @lambda f: f
... def foo(): pass
...

Try using the ternary operator if else ...

>>> x = lambda f: f
>>> y = lambda f: f
>>> @x if True else y
... def foo(): pass
...

Of course, you can also use arrays.

>>> deco = [lambda f: f]
>>> @deco[0]
... def foo(): pass
...

Impressions

  >>> @x := staticmethod  #Substitution formula(3.From 9)
  ... def foo(): pass
  ...

Recommended Posts

I read PEP 614 (Relaxing Grammar Restrictions On Decorators)
I read PEP 613 (Explicit Type Aliases)
I read PEP 612 (Parameter Specification Variables)
I read PEP 604 (Complementary syntax for Union []).
I read PEP-362 (Function Signature Object) Memo
I read PEP 618 (Add Optional Length-Checking To zip)
I read PEP 584 (Add Union Operators To dict)
I read PEP-593 (Flexible function and variable annotations)
I read an introductory book on natural language processing
I read PEP-544 (Protocols: Structural subtyping (static duck typing)).
I read PEP 585 (Type Hinting Generics In Standard Collections)