What are Python 3.8 Assignment Expressions?

14

Assignment expressions are defined in the PEP 572 that was approved to be implemented in version 3.8 of Python.

  • But what are the assignment expressions and when should they be used?
  • What kind of problem does your implementation seek to solve?
  • Why did your implementation cause controversy in the Python community? Does it go against the "principles" of language?
asked by anonymous 25.08.2018 / 00:41

1 answer

12

The answer goes by levels.

  • Simple concept:
  • Complete concept:
  • Example:
  • How to use:
  • References:

Simple concept:

We can say "simple" what is to define a variable and pass it as value at the same time.

Ex:

# $ entrada do código 
# > saída do código 

$ a = 1
>
$ a
> 1

So what you can go on to do is put the two together in a single line. Staying like this:

$ a := 1    # Você definiu a variável e ao mesmo tempo ela passa o valor adiante.
> 1

Complete concept:

Abstract:

It is a proposal to define variables as an expression. (NAME : = expr)

  • added a new exception "TargetScopeError".

Motivation:

Naming the result of an expression is an important part of programming, thus allowing it to be used in place of a long expression and allowing reuse.

...
a = foo(x)
baa(a)
cee(a)
...

Now it can be:

...
baa(a:=foo(x))
cee(a)
...

The real importance:

I will not quote directly here because it is great and it is good to read everything, the link is at the end of the answer. If anyone wants I will summarize and change here. And yes, there were discussions if this is pythonic.

Syntax:

Many arbitrary contexts in which Python expressions can be used. This is the form of NAME: = expr where expr is a valid Python expression as a tuple with no parentheses and NAME is the identifier.

$ a = 3,1
$ type(a)
> <class 'tuple'>

regex

if (match := pattern.search(data)) is not None:
    # Do something with match

Loop can not be easily rewritten using 2 iterative arguments.

while chunk := file.read(8192):
   process(chunk)

Analyzing value is computationally expensive

[y := f(x), y**2, y**3]

Shares the subexpression between a filter and an "exit."

filtered_data = [y for x in data if (y := f(x)) is not None]

Exceptional cases: (Invalid and valid but not recommended.)

Tomorrow calmly, because of my schedule, but it has in the PEP 572 reference link at the end of the answer. :) If it is to use recommend the reading.

Example:

If someone wants to, I create a more complex example, but I'll leave one that I found very simple but demonstrative that is in PEP itself.

# Computar uma lista de somas parciais e retornar o total
total = 0
partial_sums = [total := total + v for v in values]
print("Total:", total)

# Legal né :)

Reference:

PEP 572 - Assignment Expressions

Example Usage - VIDEO - EN

Sorry for the mistakes, what I can improve, just say in the comments.

See you soon :)

    
25.08.2018 / 03:56