• Python »
  • 3.12.2 Documentation »
  • The Python Language Reference »
  • 7. Simple statements
  • Theme Auto Light Dark |

7. Simple statements ¶

A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. The syntax for simple statements is:

7.1. Expression statements ¶

Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value None ). Other uses of expression statements are allowed and occasionally useful. The syntax for an expression statement is:

An expression statement evaluates the expression list (which may be a single expression).

In interactive mode, if the value is not None , it is converted to a string using the built-in repr() function and the resulting string is written to standard output on a line by itself (except if the result is None , so that procedure calls do not cause any output.)

7.2. Assignment statements ¶

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:

(See section Primaries for the syntax definitions for attributeref , subscription , and slicing .)

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section The standard type hierarchy ).

Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.

If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target.

If the target list contains one target prefixed with an asterisk, called a “starred” target: The object must be an iterable with at least as many items as there are targets in the target list, minus one. The first items of the iterable are assigned, from left to right, to the targets before the starred target. The final items of the iterable are assigned to the targets after the starred target. A list of the remaining items in the iterable is then assigned to the starred target (the list can be empty).

Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

Assignment of an object to a single target is recursively defined as follows.

If the target is an identifier (name):

If the name does not occur in a global or nonlocal statement in the current code block: the name is bound to the object in the current local namespace.

Otherwise: the name is bound to the object in the global namespace or the outer namespace determined by nonlocal , respectively.

The name is rebound if it was already bound. This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called.

If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an object with assignable attributes; if this is not the case, TypeError is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily AttributeError ).

Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the right-hand side expression, a.x can access either an instance attribute or (if no instance attribute exists) a class attribute. The left-hand side target a.x is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of a.x do not necessarily refer to the same attribute: if the right-hand side expression refers to a class attribute, the left-hand side creates a new instance attribute as the target of the assignment:

This description does not necessarily apply to descriptor attributes, such as properties created with property() .

If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

If the primary is a mutable sequence object (such as a list), the subscript must yield an integer. If it is negative, the sequence’s length is added to it. The resulting value must be a nonnegative integer less than the sequence’s length, and the sequence is asked to assign the assigned object to its item with that index. If the index is out of range, IndexError is raised (assignment to a subscripted sequence cannot add new items to a list).

If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping’s key type, and the mapping is then asked to create a key/value pair which maps the subscript to the assigned object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed).

For user-defined objects, the __setitem__() method is called with appropriate arguments.

If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it.

CPython implementation detail: In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages.

Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2] :

The specification for the *target feature.

7.2.1. Augmented assignment statements ¶

Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement:

(See section Primaries for the syntax definitions of the last three symbols.)

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place , meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the right-hand side. For example, a[i] += f(x) first looks-up a[i] , then it evaluates f(x) and performs the addition, and lastly, it writes the result back to a[i] .

With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.

For targets which are attribute references, the same caveat about class and instance attributes applies as for regular assignments.

7.2.2. Annotated assignment statements ¶

Annotation assignment is the combination, in a single statement, of a variable or attribute annotation and an optional assignment statement:

The difference from normal Assignment statements is that only a single target is allowed.

For simple names as assignment targets, if in class or module scope, the annotations are evaluated and stored in a special class or module attribute __annotations__ that is a dictionary mapping from variable names (mangled if private) to evaluated annotations. This attribute is writable and is automatically created at the start of class or module body execution, if annotations are found statically.

For expressions as assignment targets, the annotations are evaluated if in class or module scope, but not stored.

If a name is annotated in a function scope, then this name is local for that scope. Annotations are never evaluated and stored in function scopes.

If the right hand side is present, an annotated assignment performs the actual assignment before evaluating annotations (where applicable). If the right hand side is not present for an expression target, then the interpreter evaluates the target except for the last __setitem__() or __setattr__() call.

The proposal that added syntax for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments.

The proposal that added the typing module to provide a standard syntax for type annotations that can be used in static analysis tools and IDEs.

Changed in version 3.8: Now annotated assignments allow the same expressions in the right hand side as regular assignments. Previously, some expressions (like un-parenthesized tuple expressions) caused a syntax error.

7.3. The assert statement ¶

Assert statements are a convenient way to insert debugging assertions into a program:

The simple form, assert expression , is equivalent to

The extended form, assert expression1, expression2 , is equivalent to

These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O ). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.

Assignments to __debug__ are illegal. The value for the built-in variable is determined when the interpreter starts.

7.4. The pass statement ¶

pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

7.5. The del statement ¶

Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints.

Deletion of a target list recursively deletes each target, from left to right.

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.

Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).

Changed in version 3.2: Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block.

7.6. The return statement ¶

return may only occur syntactically nested in a function definition, not within a nested class definition.

If an expression list is present, it is evaluated, else None is substituted.

return leaves the current function call with the expression list (or None ) as return value.

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.

In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.

In an asynchronous generator function, an empty return statement indicates that the asynchronous generator is done and will cause StopAsyncIteration to be raised. A non-empty return statement is a syntax error in an asynchronous generator function.

7.7. The yield statement ¶

A yield statement is semantically equivalent to a yield expression . The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. For example, the yield statements

are equivalent to the yield expression statements

Yield expressions and statements are only used when defining a generator function, and are only used in the body of the generator function. Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

For full details of yield semantics, refer to the Yield expressions section.

7.8. The raise statement ¶

If no expressions are present, raise re-raises the exception that is currently being handled, which is also known as the active exception . If there isn’t currently an active exception, a RuntimeError exception is raised indicating that this is an error.

Otherwise, raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException . If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

The type of the exception is the exception instance’s class, the value is the instance itself.

A traceback object is normally created automatically when an exception is raised and attached to it as the __traceback__ attribute. You can create an exception and set your own traceback in one step using the with_traceback() exception method (which returns the same exception instance, with its traceback set to its argument), like so:

The from clause is used for exception chaining: if given, the second expression must be another exception class or instance. If the second expression is an exception instance, it will be attached to the raised exception as the __cause__ attribute (which is writable). If the expression is an exception class, the class will be instantiated and the resulting exception instance will be attached to the raised exception as the __cause__ attribute. If the raised exception is not handled, both exceptions will be printed:

A similar mechanism works implicitly if a new exception is raised when an exception is already being handled. An exception may be handled when an except or finally clause, or a with statement, is used. The previous exception is then attached as the new exception’s __context__ attribute:

Exception chaining can be explicitly suppressed by specifying None in the from clause:

Additional information on exceptions can be found in section Exceptions , and information about handling exceptions is in section The try statement .

Changed in version 3.3: None is now permitted as Y in raise X from Y .

New in version 3.3: The __suppress_context__ attribute to suppress automatic display of the exception context.

Changed in version 3.11: If the traceback of the active exception is modified in an except clause, a subsequent raise statement re-raises the exception with the modified traceback. Previously, the exception was re-raised with the traceback it had when it was caught.

7.9. The break statement ¶

break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.

It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.

If a for loop is terminated by break , the loop control target keeps its current value.

When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.

7.10. The continue statement ¶

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. It continues with the next cycle of the nearest enclosing loop.

When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.

7.11. The import statement ¶

The basic import statement (no from clause) is executed in two steps:

find a module, loading and initializing it if necessary

define a name or names in the local namespace for the scope where the import statement occurs.

When the statement contains multiple clauses (separated by commas) the two steps are carried out separately for each clause, just as though the clauses had been separated out into individual import statements.

The details of the first step, finding and loading modules, are described in greater detail in the section on the import system , which also describes the various types of packages and modules that can be imported, as well as all the hooks that can be used to customize the import system. Note that failures in this step may indicate either that the module could not be located, or that an error occurred while initializing the module, which includes execution of the module’s code.

If the requested module is retrieved successfully, it will be made available in the local namespace in one of three ways:

If the module name is followed by as , then the name following as is bound directly to the imported module.

If no other name is specified, and the module being imported is a top level module, the module’s name is bound in the local namespace as a reference to the imported module

If the module being imported is not a top level module, then the name of the top level package that contains the module is bound in the local namespace as a reference to the top level package. The imported module must be accessed using its full qualified name rather than directly

The from form uses a slightly more complex process:

find the module specified in the from clause, loading and initializing it if necessary;

for each of the identifiers specified in the import clauses:

check if the imported module has an attribute by that name

if not, attempt to import a submodule with that name and then check the imported module again for that attribute

if the attribute is not found, ImportError is raised.

otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

If the list of identifiers is replaced by a star ( '*' ), all public names defined in the module are bound in the local namespace for the scope where the import statement occurs.

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__ ; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ( '_' ). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

The wild card form of import — from module import * — is only allowed at the module level. Attempting to use it in class or function definitions will raise a SyntaxError .

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod . If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod . The specification for relative imports is contained in the Package Relative Imports section.

importlib.import_module() is provided to support applications that determine dynamically the modules to be loaded.

Raises an auditing event import with arguments module , filename , sys.path , sys.meta_path , sys.path_hooks .

7.11.1. Future statements ¶

A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python where the feature becomes standard.

The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard.

A future statement must appear near the top of the module. The only lines that can appear before a future statement are:

the module docstring (if any),

blank lines, and

other future statements.

The only feature that requires using the future statement is annotations (see PEP 563 ).

All historical features enabled by the future statement are still recognized by Python 3. The list includes absolute_import , division , generators , generator_stop , unicode_literals , print_function , nested_scopes and with_statement . They are all redundant because they are always enabled, and only kept for backwards compatibility.

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

For any given release, the compiler knows which feature names have been defined, and raises a compile-time error if a future statement contains a feature not known to it.

The direct runtime semantics are the same as for any import statement: there is a standard module __future__ , described later, and it will be imported in the usual way at the time the future statement is executed.

The interesting runtime semantics depend on the specific feature enabled by the future statement.

Note that there is nothing special about the statement:

That is not a future statement; it’s an ordinary import statement with no special semantics or syntax restrictions.

Code compiled by calls to the built-in functions exec() and compile() that occur in a module M containing a future statement will, by default, use the new syntax or semantics associated with the future statement. This can be controlled by optional arguments to compile() — see the documentation of that function for details.

A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. If an interpreter is started with the -i option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed.

The original proposal for the __future__ mechanism.

7.12. The global statement ¶

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global , although free variables may refer to globals without being declared global.

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

Names listed in a global statement must not be defined as formal parameters, or as targets in with statements or except clauses, or in a for target list, class definition, function definition, import statement, or variable annotation.

CPython implementation detail: The current implementation does not enforce some of these restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.

Programmer’s note: global is a directive to the parser. It applies only to code parsed at the same time as the global statement. In particular, a global statement contained in a string or code object supplied to the built-in exec() function does not affect the code block containing the function call, and code contained in such a string is unaffected by global statements in the code containing the function call. The same applies to the eval() and compile() functions.

7.13. The nonlocal statement ¶

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).

Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.

The specification for the nonlocal statement.

7.14. The type statement ¶

The type statement declares a type alias, which is an instance of typing.TypeAliasType .

For example, the following statement creates a type alias:

This code is roughly equivalent to:

annotation-def indicates an annotation scope , which behaves mostly like a function, but with several small differences.

The value of the type alias is evaluated in the annotation scope. It is not evaluated when the type alias is created, but only when the value is accessed through the type alias’s __value__ attribute (see Lazy evaluation ). This allows the type alias to refer to names that are not yet defined.

Type aliases may be made generic by adding a type parameter list after the name. See Generic type aliases for more.

type is a soft keyword .

New in version 3.12.

Introduced the type statement and syntax for generic classes and functions.

Table of Contents

  • 7.1. Expression statements
  • 7.2.1. Augmented assignment statements
  • 7.2.2. Annotated assignment statements
  • 7.3. The assert statement
  • 7.4. The pass statement
  • 7.5. The del statement
  • 7.6. The return statement
  • 7.7. The yield statement
  • 7.8. The raise statement
  • 7.9. The break statement
  • 7.10. The continue statement
  • 7.11.1. Future statements
  • 7.12. The global statement
  • 7.13. The nonlocal statement
  • 7.14. The type statement

Previous topic

6. Expressions

8. Compound statements

  • Report a Bug
  • Show Source

David Muller My book: Intuitive Python ↗

How to use assignment expressions in python.

10 November, 2020

This article was originally published in DigitalOcean’s public knowledge base . It has been reproduced here with some minor edits.

Introduction

Python 3.8 , released in October 2019, adds assignment expressions to Python via the := syntax. The assignment expression syntax is also sometimes called “the walrus operator” because := vaguely resembles a walrus with tusks.

Assignment expressions allow variable assignments to occur inside of larger expressions. While assignment expressions are never strictly necessary to write correct Python code, they can help make existing Python code more concise. For example, assignment expressions using the := syntax allow variables to be assigned inside of if statements, which can often produce shorter and more compact sections of Python code by eliminating variable assignments in lines preceding or following the if statement.

In this tutorial, you will use assignment expressions in several examples to produce concise sections of code.

Prerequisites

To get the most out of this tutorial, you will need:

  • Python 3.8 or above. Assignment expressions are a new feature added starting in Python 3.8.

Using Assignment Expressions in if Statements

Let’s start with an example of how you can use assignment expressions in an if statement.

Consider the following code that checks the length of a list and prints a statement:

If you run the previous code, you will receive the following output:

You initialize a list named some_list that contains three elements. Then, the if statement uses the assignment expression ((list_length := len(some_list)) to bind the variable named list_length to the length of some_list . The if statement evaluates to True because list_length is greater than 2 . You print a string using the list_length variable, which you bound initially with the assignment expression, indicating the the three-element list is too long.

Note: Assignment expressions are a new feature introduced in Python 3.8 . To run the examples in this tutorial, you will need to use Python 3.8 or higher.

Had we not used assignment expression, our code might have been slightly longer. For example:

This code sample is equivalent to the first example, but this code requires one extra standalone line to bind the value of list_length to len(some_list) .

Another equivalent code sample might just compute len(some_list) twice: once in the if statement and once in the print statement. This would avoid incurring the extra line required to bind a variable to the value of len(some_list) :

Assignment expressions help avoid the extra line or the double calculation.

Note: Assignment expressions are a helpful tool, but are not strictly necessary. Use your judgement and add assignment expressions to your code when it significantly improves the readability of a passage.

In the next section, we’ll explore using assignment expressions inside of while loops.

Using Assignment Expressions in while Loops

Assignment expressions often work well in while loops because they allow us to fold more context into the loop condition.

Consider the following example that embeds a user input function inside the while loop condition:

If you run this code, Python will continually prompt you for text input from your keyboard until you type the word stop . One example session might look like:

The assignment expression (directive := input("Enter text: ")) binds the value of directive to the value retrieved from the user via the input function. You bind the return value to the variable directive , which you print out in the body of the while loop. The while loop exits whenever the you type stop .

Had you not used an assignment expression, you might have written an equivalent input loop like:

This code is functionally identical to the one with assignment expressions, but requires four total lines (as opposed to two lines). It also duplicates the input("Enter text: ") call in two places. Certainly, there are many ways to write an equivalent while loop, but the assignment expression variant introduced earlier is compact and captures the program’s intention well.

So far, you’ve used assignment expression in if statements and while loops. In the next section, you’ll use an assignment expression inside of a list comprehension.

Using Assignment Expressions in List Comprehensions

We can also use assignment expressions in list comprehensions. List comprehensions allow you to build lists succinctly by iterating over a sequence and potentially adding elements to the list that satisfy some condition.

Consider the following example that uses a list comprehension and an assignment expression to build a list of multiplied integers:

If you run the previous code, you will receive the following:

You define a function named slow_calculation that multiplies the given number x with itself. A list comprehension then iterates through 0 , 1 , and 2 returned by range(3) . An assignment expression binds the value result to the return of slow_calculation with i . You add the result to the newly built list as long as it is greater than 0. In this example, 0 , 1 , and 2 are all multiplied with themselves, but only the results 1 ( 1 * 1 ) and 4 ( 2 * 2 ) satisfy the greater than 0 condition and become part of the final list [1, 4] .

The slow_calculation function isn’t necessarily slow in absolute terms, but is meant to illustrate an important point about effeciency. Consider an alternate implementation of the previous example without assignment expressions:

Running this, you will receive the following output:

In this variant of the previous code, you use no assignment expressions. Instead, you call slow_calculation up to two times: once to ensure slow_calculation(i) is greater than 0 , and potentially a second time to add the result of the calculation to the final list. 0 is only multiplied with itself once because 0 * 0 is not greater than 0 . The other results, however, are doubly calculated because they satisfy the greater than 0 condition, and then have their results recalculated to become part of the final list [1, 4] .

You’ve now combined assignment expressions with list comprehensions to create blocks of code that are both efficient and concise.

In this tutorial, you used assignment expressions to make compact sections of Python code that assign values to variables inside of if statements, while loops, and list comprehensions.

For more information on other assignment expressions, you can view PEP 572 —the document that initially proposed adding assignment expressions to Python.

Editor: Kathryn Hancox

davidmuller.github.io / Home / My book: Intuitive Python ↗

Python walrus operator (Python 3.8 assignment expression)

Python walrus operator (Python 3.8 assignment expression)

The “Python walrus operator”, officially known as the assignment expression operator, was introduced in Python 3.8. It’s symbolized by a colon followed by an equal sign := .

The Python community refers to it as the “walrus operator” due to its resemblance to a pair of eyes and tusks, like that of a walrus.

  • 1 The Need for the Walrus Operator
  • 2 Syntax of the Walrus Operator
  • 3 Using in If Statements and While Loops
  • 4 Using in List Comprehensions
  • 5 Walrus Operator with Data Structures
  • 6 When to Use and When Not
  • 7 Compatibility and Version Support
  • 8 Tips for Transitioning from Traditional Python Syntax

The Need for the Walrus Operator

Before the introduction of the walrus operator, Python developers had to assign values to variables in one line and use them in comparisons in the next.

This often resulted in multiple lines of code for simple operations.

In this code snippet, we had to write two lines to assign the value and then use it for comparison.

The walrus operator allows developers to assign and use variables within the same expression.

Syntax of the Walrus Operator

The syntax of the walrus operator is relatively straightforward. It involves a variable, a walrus operator := , and an expression.

Remember to enclose the assignment expression in parentheses.

In this case, the walrus operator assigns the value 10 to value and also returns the value 10 . However, remember that you can’t use this operator in a stand-alone statement, unlike the standard assignment operator = .

Using in If Statements and While Loops

The walrus operator can be used in if statements and while loops to make the code more concise. Here’s how to use the walrus operator in if statements.

In this example, the walrus operator is used to assign the length of input_value to value and compare it with 4 in the same line.

As the length of the string “Hello” is 5 , which is greater than 4 , the message is printed.

You can also use the walrus operator in while loops to make the code more concise:

In this example, the walrus operator is used to assign the value of input("Enter a non-empty string: ") to value and compare it to an empty string "" .

The loop continues to execute as long as the user enters an empty string.

As soon as a non-empty string is entered, it breaks out of the loop and prints the non-empty string.

Using in List Comprehensions

The walrus operator is handy when working with list comprehensions in Python. This allows for more complex calculations within list comprehensions without calling a function multiple times.

In this example, the walrus operator assigns the value of random.randint(1, 20) to number and checks if it’s even. If it is, it adds the number to the list. This results in a list of random even numbers.

Walrus Operator with Data Structures

The walrus operator can be effectively used with Python’s data structures like lists, sets, and dictionaries, as well as in comprehensions for these data structures.

In this example, the walrus operator is used to assign the maximum and minimum values of the numbers list to the variables num_max and num_min within the dictionary comprehension.

When to Use and When Not

While the walrus operator offers many advantages, it should be used judiciously. It’s best suited to situations where using it can make the code more concise without sacrificing readability.

For example, it’s beneficial when a variable needs to be assigned and used in the same line, such as within conditions or list comprehensions. On the other hand, it may not be suitable for complex expressions, as it can make the code difficult to read and understand.

Similarly, in situations where a stand-alone assignment is needed, the traditional assignment operator = should be used instead of the walrus operator.

Compatibility and Version Support

The walrus operator is a new operator introduced in Python 3.8. As such, it is not available in Python versions prior to 3.8.

For new projects or projects that are guaranteed to run on Python 3.8 or later, feel free to use the walrus operator whenever it improves your code’s clarity and conciseness.

If you’re working on a project that needs to support older Python versions, you should avoid using the walrus operator or rewrite your code in the new syntax.

Tips for Transitioning from Traditional Python Syntax

Transitioning to use the walrus operator from traditional Python syntax can be straightforward with the following tips:

  • Start using the walrus operator in simple use cases like if conditions or while loops.
  • Gradually move to more advanced uses like list comprehensions and function calls.
  • Always consider the readability of your code. If the use of the walrus operator makes your code hard to read, it might be better to stick with traditional syntax.

Resource : https://docs.python.org/3/whatsnew/3.8.html

  • Share on Facebook
  • Tweet on Twitter

Mokhtar Ebrahim

Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.

Related posts

  • Modulo Operator (%) In Python (Real-World Examples)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Python 3.8 Walrus Operator (Assignment Expression)

The release of Python 3.8 came with an exciting new feature: the Walrus Operator . It’s an assignment expression , or in simpler terms an assignment inside an expression.

Python 3.8 Walrus Operator (Assignment Expression)

Let’s dive into practice immediately and look at the following code:

We have a list of users whose data is represented in a dictionary. We want to count the number of approved users. The entry 'approved' is set to True if the user was approved. If the user wasn’t approved, the entry 'approved' can be False or absent.

Inside the for-loop we retrieve the value of 'approved' from the user dictionary first and assign it to the variable appr . Second, we use the if-statement to check if the value of appr is either True or False / None . Using the Walrus Operator we can merge these two steps into one so that our loop would look like this:

Try It Yourself:

Now you can see how we the assignment and the if-expression have become one single step in our code. And this is why it’s called assignment expression .

Applications

The Walrus Operator has a wide range of applications which we want to examine in the following paragraphs.

Walrus Operator with Regex

Regular Expressions are a powerful tool in programming. We even wrote an entire book about them! (Check out “The Smartest Way to Learn Python Regex” .)

Together with Regular Expressions the Walrus Operator can be used to check and assign a match in one line.

Here is the code:

I suggest, as an exercise, you try to rewrite the code from above without the walrus operator.

If you need a hint, check the first paragraph of this article.

Read File byte-wise Using the Walrus Operator

The Walrus Operator can be nicely used for reading chunks of data byte-wise from a file.

In this case it would be more complicated to rewrite the code without the Walrus Operator since it would require a while True loop and inside the loop you’d have to check what you read. If the file.read() method returns None you break out of the for-loop, else you process the chunk. So, here the Walrus Operator comes in very handy.

Walrus Operator in List Comprehensions

The Walrus Operator can be used in list comprehensions so that a function doesn’t have to be called multiple times.

In the if-statement of the list comprehension we call function f and assign the value to y if the result of f(x) makes the condition become True .

If we want to add the result of f(x) to the list we’d have to call f(x) again without the Walrus Operator or write a for-loop where we can use a temporary variable.

By using the Walrus Operator in a list comprehension we can avoid multiple function calls and reduce the lines of code .

Reuse a Value That Is Expensive to Compute

I consider this application of the Walrus Operator rather a curiosity but for the sake of completeness I’d like to mention it. In this case it reduces the number of lines of code that you have to write by one.

Instead of writing:

you can shorten the code by using the Walrus Operator to one single line:

I don’t recommend this use of the Walrus Operator since it reduces readability. It’s very easy now to miss the point where the initial value of y gets computed.

The Walrus Operator is a cool new feature but don’t over-use it. As we have seen in the examples above, it helps to write code faster because we need less code. However, readability is also very important since code is written only once but read multiple times. If you save a minute writing your code but then spend two hours debugging it, it’s clearly not worth it.

This ambiguity has also sparked controversy around the Walrus Operand and in my opinion, as many times in life, the middle way is the way to go.

Where to Go From Here?

Want to start earning a full-time income with Python—while working only part-time hours? Then join our free Python Freelancer Webinar .

It shows you exactly how you can grow your business and Python skills to a point where you can work comfortable for 3-4 hours from home and enjoy the rest of the day (=20 hours) spending time with the persons you love doing things you enjoy to do.

Become a Python freelancer now!

5. Assignment Expressions

By Bernd Klein . Last modified: 30 Nov 2023.

On this page ➤

Introduction

walrus

This section in our Python tutorial explores the "assignment expression operator" affectionately known to many as "the walrus operator. So, you can call it either the "walrus operator" or the "assignment expression operator," and people in the Python programming community will generally understand what you mean. Despite being introduced in Python version 3.8, we can still view it as a relatively recent addition to the language. The assignment expressions have been discussed in PEP 572 and this is what was written about the naming:

The purpose of this feature is not a new way to assign objects to variables, but it gives programmers a convenient way to assign variables in the middle of expressions.

You might still be curious about the origin of the term "walrus operator." It's affectionately named this way because, with a touch of imagination, the operator's characters resemble the eyes and tusks of a walrus.

We will introduce the assignment expression by comparing it first with a simple assignment statement. A simple assignment statement can also be replaced by an assignment expression, even though it looks clumsy and is definitely not the intended use case of it:

First you may wonder about the brackets, when you look at the assignment expression. It is not meant as a replacement for the simple "assignment statement". Its primary role is to be utilized within expressions

The following code shows a proper usecase:

Though you may argue that the following code might be even clearer:

Here's another Python code example that demonstrates a similar scenario. First with the walrus operator:

Now without the walrus operator:

Live Python training

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Beneficial applications

Now, let's explore some examples where the usage of the assignment expression is really beneficial compared to code not using it.

You can observe that if we choose to avoid using the assignment expression in the list comprehension, we would need to call the function twice. So using the assgment expression makes the code in this context more efficient.

Use Case: Regular Expressions

There is also a great advantage when we use regular expressions. Like in our previous examples we present again two similiar code snippets, the first one without and the second one with the walrus operator:

Now, the code using assignment expressions:

Assignment Expression in File Reading

Fixed-width files.

Files in which each line has the same length are often referred to as "fixed-width" or "fixed-length" files. In these files, each line (or record) is structured so that it contains a predefined number of characters, and the fields within the lines have fixed positions. The files can be read by using the read -method and the walrus operator:

Now the same in traditional coding style:

The benefits for the most recent code snippet are

  • It uses a more traditional coding style, which may be more familiar to some developers.
  • It assigns and uses the data variable explicitly, making the code easier to understand for those not familiar with assignment expressions.

However, a significant drawback of this approach is that it requires the explicit assignment and reassignment of the data variable, which can be seen as less concise and somewhat less elegant.

Using readline

Most people use a for loop to iterator over a text file line by line. With the walrus operator, we can also elegantly go through a text using the method readline :

Code snippet using readline but not the assignment expression:

Now with the walrus operator:

Another Use Case

In the chapter on while loops of our Python Tutorial, we had a little number guessing game:

As you can see, we had to initialize guess to zero to be able to enter the loop. We can do the initialization directly in the loop condition with an assignment expression and simplify the whole code by this:

Critiques of the Walrus Operator in Python

the Python walrus

We said in the beginning of this page that some Python programmers longed for this construct for quite a while. One reason why it was not introduced earlier was the fact that it can also be used to write code which is less readable. In fact, the application of the walrus operator contradicts several principles highlighted in the Zen of Python. To grasp these contraventions, let's delve into the ensuing scenarios.

The Zen of Python says "Explicit is better than implicit". The walrus operator violates this requirement of the Zen of Python. This means that explicit operations are always better than implicit operations. The walrus operator assigns a value to a variable and implicitly returns the value as well. Therefore, it does not align with the concept of "Explicit is better than implicit."

The following code snippet is shows an extreme example which is not recommended to use:

What are your thoughts on the following piece of code using the Python assignment operator inside of a print function call?

These Python code snipets certainly violate two other demands of the Zen of Python:

  • Beautiful is Better Than Ugly
  • Complex is Better Than Complicated

The principle "There should be one and preferably only one obvious way to do it" from the Zen of Python emphasizes the importance of having a clear and singular approach. When we have the option to separate assignment and return operations into distinct statements, opting for the less readable and more complex walrus operator contradicts this principle.

Upcoming online Courses

On this page

Mouse Vs Python

Python 3 – Assignment Expressions

I recently came across PEP 572 , which is a proposal for adding assignment expressions to Python 3.8 from Chris Angelico, Tim Peters and Guido van Rossum himself! I decided to check it out and see what an assignment expression was. The idea is actually quite simple. The Python core developers want a way to assign variables within an expression using the following notation:

This topic has had a LOT of arguments about it and you can read the details on the Python-Dev Google group if you want to. I personally found that reading through the various pros and cons put forth by Python’s core development community to be very insightful.

Regardless, let’s look at some of the examples from PEP 572 to see if we can figure out how you might use an assignment expression yourself.

In these 3 examples, we are creating a variable in the expression statement itself. The first example creates the variable, match , by assigning it the result of the regex pattern search. The second example assigns the variable, value , to the result of calling a function in the while loop’s expression. Finally we assign the result of calling f(x) to the variable y inside of a list comprehension.

One of the most interesting features of assignment expressions (to me at least), is that they can be used in contexts that an assignment statement cannot, such as in a lambda or the previously mentioned comprehension. However they also do NOT support some things that assignment statements can do. For example, you cannot to multiple target assignment:

You can see a full list of differences in the PEP

There is a lot more information in the PEP that covers a few other examples, talks about rejected alternatives and scope.

Related Reading

  • PEP 572 — Assignment Expressions
  • Reddit: Accidentally override local variables
  • Reddit on PEP 572

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 577 – Augmented Assignment Expressions

Pep withdrawal, augmented assignment expressions, adding an inline assignment operator, assignment operator precedence, augmented assignment to names in block scopes, augmented assignment to names in scoped expressions, allowing complex assignment targets, augmented assignment or name binding only, postponing a decision on expression level target declarations, ignoring scoped expressions when determining augmented assignment targets, treating inline assignment as an augmented assignment variant, disallowing augmented assignments in class level scoped expressions, comparison operators vs assignment operators, simplifying retry loops, simplifying if-elif chains, capturing intermediate values from comprehensions, allowing lambda expressions to act more like re-usable code thunks, relationship with pep 572, acknowledgements.

While working on this PEP, I realised that it didn’t really address what was actually bothering me about PEP 572 ’s proposed scoping rules for previously unreferenced assignment targets, and also had some significant undesirable consequences (most notably, allowing >>= and <<= as inline augmented assignment operators that meant something entirely different from the >= and <= comparison operators).

I also realised that even without dedicated syntax of their own, PEP 572 technically allows inline augmented assignments to be written using the operator module:

The restriction to simple names as inline assignment targets means that the target expression can always be repeated without side effects, and thus avoids the ambiguity that would arise from allowing actual embedded augmented assignments (it’s still a bad idea, since it would almost certainly be hard for humans to read, this note is just about the theoretical limits of language level expressiveness).

Accordingly, I withdrew this PEP without submitting it for pronouncement. At the time I also started writing a replacement PEP that focused specifically on the handling of assignment targets which hadn’t already been declared as local variables in the current scope (for both regular block scopes, and for scoped expressions), but that draft never even reached a stage where I liked it better than the ultimately accepted proposal in PEP 572 , so it was never posted anywhere, nor assigned a PEP number.

This is a proposal to allow augmented assignments such as x += 1 to be used as expressions, not just statements.

As part of this, NAME := EXPR is proposed as an inline assignment expression that uses the new augmented assignment scoping rules, rather than implicitly defining a new local variable name the way that existing name binding statements do. The question of allowing expression level local variable declarations at function scope is deliberately separated from the question of allowing expression level name bindings, and deferred to a later PEP.

This PEP is a direct competitor to PEP 572 (although it borrows heavily from that PEP’s motivation, and even shares the proposed syntax for inline assignments). See Relationship with PEP 572 for more details on the connections between the two PEPs.

To improve the usability of the new expressions, a semantic split is proposed between the handling of augmented assignments in regular block scopes (modules, classes, and functions), and the handling of augmented assignments in scoped expressions (lambda expressions, generator expressions, and comprehensions), such that all inline assignments default to targeting the nearest containing block scope.

A new compile time TargetNameError is added as a subclass of SyntaxError to handle cases where it is deemed to be currently unclear which target is expected to be rebound by an inline assignment, or else the target scope for the inline assignment is considered invalid for another reason.

Syntax and semantics

The language grammar would be adjusted to allow augmented assignments to appear as expressions, where the result of the augmented assignment expression is the same post-calculation reference as is being bound to the given target.

For example:

For mutable targets, this means the result is always just the original object:

Augmented assignments to attributes and container subscripts will be permitted, with the result being the post-calculation reference being bound to the target, just as it is for simple name targets:

In these cases, __getitem__ and __getattribute__ will not be called after the assignment has already taken place (they will only be called as needed to evaluate the in-place operation).

Given only the addition of augmented assignment expressions, it would be possible to abuse a symbol like |= as a general purpose assignment operator by defining a Target wrapper type that worked as follows:

This is similar to the way that storing a single reference in a list was long used as a workaround for the lack of a nonlocal keyword, and can still be used today (in combination with operator.itemsetter ) to work around the lack of expression level assignments.

Rather than requiring such workarounds, this PEP instead proposes that PEP 572 ’s “NAME := EXPR” syntax be adopted as a new inline assignment expression that uses the augmented assignment scoping rules described below.

This cleanly handles cases where only the new value is of interest, and the previously bound value (if any) can just be discarded completely.

Note that for both simple names and complex assignment targets, the inline assignment operator does not read the previous reference before assigning the new one. However, when used at function scope (either directly or inside a scoped expression), it does not implicitly define a new local variable, and will instead raise TargetNameError (as described for augmented assignments below).

To preserve the existing semantics of augmented assignment statements, inline assignment operators will be defined as being of lower precedence than all other operators, include the comma pseudo-operator. This ensures that when used as a top level expression the entire right hand side of the expression is still interpreted as the value to be processed (even when that value is a tuple without parentheses).

The difference this introduces relative to PEP 572 is that where (n := first, second) sets n = first in PEP 572 , in this PEP it would set n = (first, second) , and getting the first meaning would require an extra set of parentheses ( ((n := first), second) ).

PEP 572 quite reasonably notes that this results in ambiguity when assignment expressions are used as function call arguments. This PEP resolves that concern a different way by requiring that assignment expressions be parenthesised when used as arguments to a function call (unless they’re the sole argument).

This is a more relaxed version of the restriction placed on generator expressions (which always require parentheses, except when they’re the sole argument to a function call).

No target name binding changes are proposed for augmented assignments at module or class scope (this also includes code executed using “exec” or “eval”). These will continue to implicitly declare a new local variable as the binding target as they do today, and (if necessary) will be able to resolve the name from an outer scope before binding it locally.

At function scope, augmented assignments will be changed to require that there be either a preceding name binding or variable declaration to explicitly establish the target name as being local to the function, or else an explicit global or nonlocal declaration. TargetNameError , a new SyntaxError subclass, will be raised at compile time if no such binding or declaration is present.

For example, the following code would compile and run as it does today:

The follow examples would all still compile and then raise an error at runtime as they do today:

Whereas the following would raise a compile time DeprecationWarning initially, and eventually change to report a compile time TargetNameError :

As a conservative implementation approach, the compile time function name resolution change would be introduced as a DeprecationWarning in Python 3.8, and then converted to TargetNameError in Python 3.9. This avoids potential problems in cases where an unused function would currently raise UnboundLocalError if it was ever actually called, but the code is actually unused - converting that latent runtime defect to a compile time error qualifies as a backwards incompatible change that requires a deprecation period.

When augmented assignments are used as expressions in function scope (rather than as standalone statements), there aren’t any backwards compatibility concerns, so the compile time name binding checks would be enforced immediately in Python 3.8.

Similarly, the new inline assignment expressions would always require explicit predeclaration of their target scope when used as part of a function, at least for Python 3.8. (See the design discussion section for notes on potentially revisiting that restriction in the future).

Scoped expressions is a new collective term being proposed for expressions that introduce a new nested scope of execution, either as an intrinsic part of their operation (lambda expressions, generator expressions), or else as a way of hiding name binding operations from the containing scope (container comprehensions).

Unlike regular functions, these scoped expressions can’t include explicit global or nonlocal declarations to rebind names directly in an outer scope.

Instead, their name binding semantics for augmented assignment expressions would be defined as follows:

  • augmented assignment targets used in scoped expressions are expected to either be already bound in the containing block scope, or else have their scope explicitly declared in the containing block scope. If no suitable name binding or declaration can be found in that scope, then TargetNameError will be raised at compile time (rather than creating a new binding within the scoped expression).
  • if the containing block scope is a function scope, and the target name is explicitly declared as global or nonlocal , then it will be use the same scope declaration in the body of the scoped expression
  • if the containing block scope is a function scope, and the target name is a local variable in that function, then it will be implicitly declared as nonlocal in the body of the scoped expression
  • if the containing block scope is a class scope, than TargetNameError will always be raised, with a dedicated message indicating that combining class scopes with augmented assignments in scoped expressions is not currently permitted.
  • if a name is declared as a formal parameter (lambda expressions), or as an iteration variable (generator expressions, comprehensions), then that name is considered local to that scoped expression, and attempting to use it as the target of an augmented assignment operation in that scope, or any nested scoped expression, will raise TargetNameError (this is a restriction that could potentially be lifted later, but is being proposed for now to simplify the initial set of compile time and runtime semantics that needs to be covered in the language reference and handled by the compiler and interpreter)

For example, the following code would work as shown:

While the following examples would all raise TargetNameError :

As augmented assignments currently can’t appear inside scoped expressions, the above compile time name resolution exceptions would be included as part of the initial implementation rather than needing to be phased in as a potentially backwards incompatible change.

Design discussion

The initial drafts of this PEP kept PEP 572 ’s restriction to single name targets when augmented assignments were used as expressions, allowing attribute and subscript targets solely for the statement form.

However, enforcing that required varying the permitted targets based on whether or not the augmented assignment was a top level expression or not, as well as explaining why n += 1 , (n += 1) , and self.n += 1 were all legal, but (self.n += 1) was prohibited, so the proposal was simplified to allow all existing augmented assignment targets for the expression form as well.

Since this PEP defines TARGET := EXPR as a variant on augmented assignment, that also gained support for assignment and subscript targets.

PEP 572 makes a reasonable case that the potential use cases for inline augmented assignment are notably weaker than those for inline assignment in general, so it’s acceptable to require that they be spelled as x := x + 1 , bypassing any in-place augmented assignment methods.

While this is at least arguably true for the builtin types (where potential counterexamples would probably need to focus on set manipulation use cases that the PEP author doesn’t personally have), it would also rule out more memory intensive use cases like manipulation of NumPy arrays, where the data copying involved in out-of-place operations can make them impractical as alternatives to their in-place counterparts.

That said, this PEP mainly exists because the PEP author found the inline assignment proposal much easier to grasp as “It’s like += , only skipping the addition step”, and also liked the way that that framing provides an actual semantic difference between NAME = EXPR and NAME := EXPR at function scope.

That difference in target scoping behaviour means that the NAME := EXPR syntax would be expected to have two primary use cases:

  • as a way of allowing assignments to be embedded as an expression in an if or while statement, or as part of a scoped expression
  • as a way of requesting a compile time check that the target name be previously declared or bound in the current function scope

At module or class scope, NAME = EXPR and NAME := EXPR would be semantically equivalent due to the compiler’s lack of visibility into the set of names that will be resolvable at runtime, but code linters and static type checkers would be encouraged to enforce the same “declaration or assignment required before use” behaviour for NAME := EXPR as the compiler would enforce at function scope.

At least for Python 3.8, usage of inline assignments (whether augmented or not) at function scope would always require a preceding name binding or scope declaration to avoid getting TargetNameError , even when used outside a scoped expression.

The intent behind this requirement is to clearly separate the following two language design questions:

  • Can an expression rebind a name in the current scope?
  • Can an expression declare a new name in the current scope?

For module global scopes, the answer to both of those questions is unequivocally “Yes”, because it’s a language level guarantee that mutating the globals() dict will immediately impact the runtime module scope, and global NAME declarations inside a function can have the same effect (as can importing the currently executing module and modifying its attributes).

For class scopes, the answer to both questions is also “Yes” in practice, although less unequivocally so, since the semantics of locals() are currently formally unspecified. However, if the current behaviour of locals() at class scope is taken as normative (as PEP 558 proposes), then this is essentially the same scenario as manipulating the module globals, just using locals() instead.

For function scopes, however, the current answers to these two questions are respectively “Yes” and “No”. Expression level rebinding of function locals is already possible thanks to lexically nested scopes and explicit nonlocal NAME expressions. While this PEP will likely make expression level rebinding more common than it is today, it isn’t a fundamentally new concept for the language.

By contrast, declaring a new function local variable is currently a statement level action, involving one of:

  • an assignment statement ( NAME = EXPR , OTHER_TARGET = NAME = EXPR , etc)
  • a variable declaration ( NAME : EXPR )
  • a nested function definition
  • a nested class definition
  • a with statement
  • an except clause (with limited scope of access)

The historical trend for the language has actually been to remove support for expression level declarations of function local names, first with the introduction of “fast locals” semantics (which made the introduction of names via locals() unsupported for function scopes), and again with the hiding of comprehension iteration variables in Python 3.0.

Now, it may be that in Python 3.9, we decide to revisit this question based on our experience with expression level name binding in Python 3.8, and decide that we really do want expression level function local variable declarations as well, and that we want NAME := EXPR to be the way we spell that (rather than, for example, spelling inline declarations more explicitly as NAME := EXPR given NAME , which would permit them to carry type annotations, and also permit them to declare new local variables in scoped expressions, rather than having to pollute the namespace in their containing scope).

But the proposal in this PEP is that we explicitly give ourselves a full release to decide how much we want that feature, and exactly where we find its absence irritating. Python has survived happily without expression level name bindings or declarations for decades, so we can afford to give ourselves a couple of years to decide if we really want both of those, or if expression level bindings are sufficient.

When discussing possible binding semantics for PEP 572 ’s assignment expressions, Tim Peters made a plausible case [1] , [2] , [3] for assignment expressions targeting the containing block scope, essentially ignoring any intervening scoped expressions.

This approach allows use cases like cumulative sums, or extracting the final value from a generator expression to be written in a relatively straightforward way:

Guido also expressed his approval for this general approach [4] .

The proposal in this PEP differs from Tim’s original proposal in three main areas:

  • it applies the proposal to all augmented assignment operators, not just a single new name binding operator
  • as far as is practical, it extends the augmented assignment requirement that the name already be defined to the new name binding operator (raising TargetNameError rather than implicitly declaring new local variables at function scope)
  • it includes lambda expressions in the set of scopes that get ignored for target name binding purposes, making this transparency to assignments common to all of the scoped expressions rather than being specific to comprehensions and generator expressions

With scoped expressions being ignored when calculating binding targets, it’s once again difficult to detect the scoping difference between the outermost iterable expressions in generator expressions and comprehensions (you have to mess about with either class scopes or attempting to rebind iteration Variables to detect it), so there’s also no need to tinker with that.

One of the challenges with PEP 572 is the fact that NAME = EXPR and NAME := EXPR are entirely semantically equivalent at every scope. This makes the two forms hard to teach, since there’s no inherent nudge towards choosing one over the other at the statement level, so you end up having to resort to “ NAME = EXPR is preferred because it’s been around longer” (and PEP 572 proposes to enforce that historical idiosyncrasy at the compiler level).

That semantic equivalence is difficult to avoid at module and class scope while still having if NAME := EXPR: and while NAME := EXPR: work sensibly, but at function scope the compiler’s comprehensive view of all local names makes it possible to require that the name be assigned or declared before use, providing a reasonable incentive to continue to default to using the NAME = EXPR form when possible, while also enabling the use of the NAME := EXPR as a kind of simple compile time assertion (i.e. explicitly indicating that the targeted name has already been bound or declared and hence should already be known to the compiler).

If Guido were to declare that support for inline declarations was a hard design requirement, then this PEP would be updated to propose that EXPR given NAME also be introduced as a way to support inline name declarations after arbitrary expressions (this would allow the inline name declarations to be deferred until the end of a complex expression rather than needing to be embedded in the middle of it, and PEP 8 would gain a recommendation encouraging that style).

While modern classes do define an implicit closure that’s visible to method implementations (in order to make __class__ available for use in zero-arg super() calls), there’s no way for user level code to explicitly add additional names to that scope.

Meanwhile, attributes defined in a class body are ignored for the purpose of defining a method’s lexical closure, which means adding them there wouldn’t work at an implementation level.

Rather than trying to resolve that inherent ambiguity, this PEP simply prohibits such usage, and requires that any affected logic be written somewhere other than directly inline in the class body (e.g. in a separate helper function).

The OP= construct as an expression currently indicates a comparison operation:

Both this PEP and PEP 572 propose adding at least one operator that’s somewhat similar in appearance, but defines an assignment instead:

This PEP then goes much further and allows all 13 augmented assignment symbols to be uses as binary operators:

Of those additional binary operators, the most questionable would be the bitshift assignment operators, since they’re each only one doubled character away from one of the inclusive ordered comparison operators.

There are currently a few different options for writing retry loops, including:

Each of the available options hides some aspect of the intended loop structure inside the loop body, whether that’s the state modification, the exit condition, or both.

The proposal in this PEP allows both the state modification and the exit condition to be included directly in the loop header:

if-elif chains that need to rebind the checked condition currently need to be written using nested if-else statements:

As with PEP 572 , this PEP allows the else/if portions of that chain to be condensed, making their consistent and mutually exclusive structure more readily apparent:

Unlike PEP 572 , this PEP requires that the assignment target be explicitly indicated as local before the first use as a := target, either by binding it to a value (as shown above), or else by including an appropriate explicit type declaration:

The proposal in this PEP makes it straightforward to capture and reuse intermediate values in comprehensions and generator expressions by exporting them to the containing block scope:

This PEP allows the classic closure usage example:

To be abbreviated as:

While the latter form is still a conceptually dense piece of code, it can be reasonably argued that the lack of boilerplate (where the “def”, “nonlocal”, and “return” keywords and two additional repetitions of the “x” variable name have been replaced with the “lambda” keyword) may make it easier to read in practice.

The case for allowing inline assignments at all is made in PEP 572 . This competing PEP was initially going to propose an alternate surface syntax ( EXPR given NAME = EXPR ), while retaining the expression semantics from PEP 572 , but that changed when discussing one of the initial motivating use cases for allowing embedded assignments at all: making it possible to easily calculate cumulative sums in comprehensions and generator expressions.

As a result of that, and unlike PEP 572 , this PEP focuses primarily on use cases for inline augmented assignment. It also has the effect of converting cases that currently inevitably raise UnboundLocalError at function call time to report a new compile time TargetNameError .

New syntax for a name rebinding expression ( NAME := TARGET ) is then added not only to handle the same use cases as are identified in PEP 572 , but also as a lower level primitive to help illustrate, implement and explain the new augmented assignment semantics, rather than being the sole change being proposed.

The author of this PEP believes that this approach makes the value of the new flexibility in name rebinding clearer, while also mitigating many of the potential concerns raised with PEP 572 around explaining when to use NAME = EXPR over NAME := EXPR (and vice-versa), without resorting to prohibiting the bare statement form of NAME := EXPR outright (such that NAME := EXPR is a compile error, but (NAME := EXPR) is permitted).

The PEP author wishes to thank Chris Angelico for his work on PEP 572 , and his efforts to create a coherent summary of the great many sprawling discussions that spawned on both python-ideas and python-dev, as well as Tim Peters for the in-depth discussion of parent local scoping that prompted the above scoping proposal for augmented assignments inside scoped expressions.

Eric Snow’s feedback on a pre-release version of this PEP helped make it significantly more readable.

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0577.rst

Last modified: 2023-10-11 12:05:51 GMT

avatar

The brand new assignment expression of Python 3.8

Python 3.8 is coming and not surprisingly it comes with a bag of new features . In this post, I’d like to present only one that I’ve been really waiting for: assignment expressions!

The problem

Whenever we see a new solution, we have to understand the problem or if there is a problem at all in the first place.

Let’s take this piece of code

Here we can identify at least two problems:

There is a solution, we can call f(s) once before the if block, and save the result in a variable!

Is that better? Well, it depends.

On the one hand, you type a bit less and if the calculations in f(s) are costly, you eliminated that expensive function call, that’s great!

On the other hand, now you have a variable that is accessible outside the if block where you orientally wanted to use it. This might be unsafe. Imagine that you create your variable as a reference to something that takes a long-chained command to retrieve.

But before you use it, you want to make a validity check.

If you create the variable outside the if block, so before making the validity check, you have to remember that if you want to use that variable later on in that function (which would probably be a bad practice anyway), you must do the validity check again.

Python 3.8 and PEP 572 provides us with the ultimate solution you probably always wanted for such issues.

You can create a variable in the if expression whose scope is only the whole if block. Isn’t that awesome?! You can do things like this, just to continue with the previous example:

By the “whole if block”, I meant that else is also included. To generalize, we can say that the scope of the variable assigned in the assignment expression is just the current scope. If it’s an if, then an if, if it’s the whole function, it’s the whole function.

What I also like a lot is that we now can simplify list comprehensions as well. Look at this example:

So, we take a list of numbers and we want to keep the ones that are squares of an integers and we also want to keep their squared and non-squared values. We have to calculate the square roots twice!

Only if I could save the square root in that generator expression! Lo and behold, now I can:

That is just super cool to me! Less typing, less calculations, faster runtime!

What do you think?

Python 3.8 introduces assignment expressions which lets us create new variables in places where we always wanted but never could in a usable way. Probably the best way to use this new feature is to create new variables in an if and use it in the scope of that block.

For more information, you can read the specs here .

As an online interpreter, for the moment you can use this .

And if you want to install python3.8 locally, you can refer to this article

Happy coding!

Further Reading

Demistify stars in python.

Okay, not all. I’ll skip the one when we use it in a string literal. I promised that I walk you through how it can be used, but let’s check first how it cannot be used. It cannot be used as part o...

Why to use the override specifier in C++ 11?

The override specifier was introduced to the language with C++11 and it is one of the easiest tool to significantly improve the maintainability of our codebases. override tells both the reader an...

How do you declare a function in C++?

Beginning of this year I came back to a C++ developer position and we are making or final steps towards complete a migration to (among others) C++11 and I decided to level up my knowledge. It’s alm...

Going down the road

Smartcuts: How Hackers, Innovators, and Icons Accelerate Success by Shane Snow

Comments powered by Disqus .

Trending Tags

Concise syntax for attribute access and assignment: e.g., `obj.(a, b, c) = 1, 2, 3`

In this proposal, I introduce a novel syntax aimed at simplifying multiple attribute access and assignment within objects.

How about if we allow this?

Rather than requiring this.

Class definitions often entail verbose patterns for initializing instance attributes, as exemplified below:

Both versions require repeated typing of self. , a mundane task. There could be several approaches to relieve this verbosity, but it’s not easy to design a feature that achieves that without bringing more evils. For example, one can think about simply allowing the omission of self. in the definition of __init__ special method, but this would sacrifice explicitness and create confusion

If we adopt the proposed syntax that I will describe shortly, it would make the code easier to type, more concise, and improve readability. And there won’t be much sacrifice in the simplicity of the language, I presume.

Please also, note that the proposed syntax is not only for improving the situation described above, but for more general cases. The example should only be considered as a motivational one. The propose syntax needs not be only used in class definitions. Also, I propose defining both accessing and assignment, not just assignment, will provide more consistency.

Multiple attribute assignment

The left-hand side of an assignment statement can be extended to support multiple attributes with fewer keystrokes, using a proposed syntax as follows:

Multiple attribute access

Similarly, accessing multiple attributes of an object can be streamlined into a single expression, which evaluates to a tuple of the accessed values:

The proposed syntax does not prevent you from nested attribute access and assignment, allowing for complex expressions involving objects with deep attribute hierarchies. Note that Python already allows arbitrarily deep LHS variable nesting e.g. (a, (b, (c, (d,e)))) = (1, (2, (3, (4, 5)))) .

Arbitrarily deep LHS variable nesting should not be encouraged to keep the code clean, but it does not mean we have to prevent it at the grammar level and I believe we allow this in Python since there is utility in allowing it. Nesting is supported in this proposal to provide a consistent user experience, but it does not always read to easier-to-read code.

Interpretation

In the most usual cases, the interpretation should be straightforward.

However, there is one syntactic form, I can imagine, that allows more than one way of interpretation.

The code above is actually quite meaningless as it will not bind the new instance(s) to any new variable and not many people won’t need to write the same pattern in practice. However, it should still be handled for completeness.

This proposal suggests Option 2 as the correct interpretation YourClass().(foo, bar) = 1, 2 should cause creation of only one YourClass instance, not two.

This proposal seeks to introduce a more succinct and readable syntax for handling multiple attribute access and assignment. I believe it will affect the majority of existing Python programmers and will enhance their productivity in class design and many other tasks. Additionally, learning this new syntax should not require extensive teaching resources as it is not hard to guess its interpretation in most cases.

I understand that such a modification to the language is a significant undertaking that requires careful consideration of its impact on the existing codebase, developer tools, and the broader programming community. Also, there are more details that need to be discussed. It would be much appreciated if you could provide feedback and suggestions.

There’s already a specific proposal here to deal with the named argument duplication that’s your motivating argument.

My unsubstantiated feeling is that self.(foo, bar, baz, qux) = foo, bar, baz, qux would cause too much difficulty in the Python parser, but it’s just a hunch.

I am certainly not enthusiastic about new language changes without a really strong benefit!

If such constructors are a chore for you, you might consider using dataclasses instead. They not only write the constructor for you, avoiding all these self.foo = foo lines, but also dataclasses automatically create other methods, like comparators and hashes.

( collections.namedtuple and typing.NamedTuple could also be used to avoid writing the constructor.)

Thank you very much for the prompt feedback. To clarify, the PEP you linked is about shortening function calling , whereas my example aimed to demonstrate the shortening of init definitions . Thus, it appears the PEP mentioned addresses a different issue.

Regarding the benefits, I believe this proposal could significantly reduce the number of lines of code, similar to the impact of star_targets the grammar upon its introduction.

I believe star_target was added to the language as it was believed to have huge benefits. The two patterns would be pretty similar and I would argue that my proposal would bring similar kinds of benefits. It’s also worth noting that my proposal could actually reduce the number of tokens, unlike the star_targets example above.

Regarding the feasibility of substituting my proposal with named tuples or other types, such replacements would not be somewhat tricky to apply for general use cases. In practice, initialization definitions often include operations other than attribute setting, making it difficult to apply these suggestions. Just to name a few, I suspect the examples below would benefit from my proposal.

  • cpython/Lib/argparse.py at main · python/cpython · GitHub
  • cpython/Lib/csv.py at v3.12.2 · python/cpython · GitHub
  • cpython/Lib/functools.py at v3.12.2 · python/cpython · GitHub

Additionally, please note that the proposal aims to enhance assignment statements in general , not just to enhance init method definition. It seems my choice of a motivational example has been misleading to you.

:smiley:

Regarding the examples, each of them would work very well with dataclasses - simply put the remaining members in __post_init__ , which is called right after the constructor goes off.

Conciseness is very rarely sufficient justification for a new language feature on its own. Typically, if you want to argue for conciseness, you should be be looking at the wider question of expressiveness - does the new feature allow developers to write clearer code that expresses their intent more accurately or understandably. Even then, it’s hard to make the case without other, more concrete benefits. Prior atr, in the form of other languages implementing a similar feature, is usually helpful, as well.

In the case of this proposal, it seems neat, but of limited value. And I’m not at all sure I find something like foo.(a, b, c) = 1, 2, 3 to be more readable than foo.a, foo.b, foo.c = 1, 2, 3 . Which brings up the point that being easy to read is far more important than being easy to write . Saving a bit of time for the writer of the code, at the expense of increasing work for the reader, is almost always a bad trade-off.

The more complex examples you give don’t immediately follow from the basic description you give - your example of "Apple".(lower(), upper()) is not something I’d have expected on an initial reading of the proposal. It’s also hard to understand how it fits with Python’s existing grammar/semantics - why are lower() and upper() not being treated as calls to global functions of those names? I think you need to write up a much more precise technical specification of your proposal if you want to avoid people dismissing it as being nothing more than a typing shortcut. You’d need to do that at some point anyway, if you plan on ever implementing this proposal, and doing it now will help you clarify the details of what you’re suggesting. Of course, writing a more detailed spec doesn’t guarantee people will like the idea any more than they do now…

I love the idea, but I’m really not enthused about the syntax - dot-openparens looks like an error. That said, though, I think there’s only one meaningful interpretation of the one you’re ambiguous on:

:slight_smile:

The biggest use-cases for this syntax do have alternatives, though. As an alternative to the __init__ example, you could use a dataclass and not assign attributes at all. I’m sure there are still plenty of places for this to be useful, though.

Question: Have you considered whether this should be extended to subscripting too? Syntactically this may be more difficult, but also, given that I’m not sold on the existing syntax, having a think about subscripting variant of the same idea might help you come up with a better syntax for attribute access too. Certainly a “broadcast” syntax would be extremely useful there, too.

How would you rewrite that one? The way I imagine it, I’d find it very much harder to read.

I am against this. Although I see its usefulness, it might lead to confusion among beginners and generally less readability. Also, it seems a bit off to me, but that’s just an opinion.

I imagined applying the new syntax to a part of the code and grouping only up to 3~4 at once, like I usually do for assigning values to multiple variables in a line.

I would re-write this,

This is already supported by operator.itemgetter , though without including method calls. With a little work, you can use methodcaller .

Not terribly readable, but I don’t find the proposed syntax an improvement over

in the first place. Not everything needs to be refactored into the least repetitive form possible.

to be far less readable than what (I assume) it replaces. I’d rather not flatten trees to lists in my head.

I find your rewrite much harder to read. The original has all the assignment targets neatly in a vertical line. With yours, I have to also search horizontally, the lines are longer, and it just looks like a mess.

[bombs-kim] Beomsoo Kim https://discuss.python.org/u/bombs-kim bombs-kim February 19 In the most usual cases, the interpretation should be straightforward. my.(bar, baz) = (5, 6) # Is equivalent to my.bar, my.baz = 5, 6|

If this expansion applies to the RHS as well, it implies that my.(bar, baz) is equivalent to the tuple constructor (my.bar, my.baz), which is inconsistent with your function call example :

print(my.(foo, bar, baz))|

Ths would need to be written as

I’m in mixed opinion in whether this is a good enough proposal. Which means it might be a good idea. I’ll try to defend the author.

I disagree. In this case, the new syntax is much clearer for the reader that everything being manipulated is foo ’s member. Although one might say that the below syntax achieves the same purpose, albeit with more lines:

No, it should definitely be the other option: single evaluation of the object.

Yeah, I prefer single evaluation, since it’s written like so. I feel such a throwaway class doesn’t make much sense, but what if it’s a getter (e.g. @property )?

I find it much easier to read.

Related Topics

  • Contributors

Regular Expressions Basic Syntax

Table of contents, regular expression syntax, practical examples.

Regular Expression Basic Syntax in Python

Regular expressions (regex) are a powerful tool for pattern matching and data extraction in text processing. Python's re module provides a comprehensive set of functions to work with regular expressions. This article dives into the syntax of regular expressions in Python, accompanied by practical examples to help you grasp the concepts better.

Regular expressions use a sequence of characters to define a search pattern. Here's a quick overview of some common regex syntax elements in Python:

  • . (Dot): Matches any single character except newline ' ' .
  • ^ (Caret): Matches the start of the string.
  • $ (Dollar): Matches the end of the string.
  • * (Asterisk): Matches 0 or more repetitions of the preceding element.
  • + (Plus): Matches 1 or more repetitions of the preceding element.
  • ? (Question Mark): Matches 0 or 1 repetition of the preceding element.
  • {m,n} (Braces): Matches from m to n repetitions of the preceding element.
  • [] (Square Brackets): Matches any single character contained within the brackets.
  • | (Pipe): Acts as a logical OR between expressions.
  • () (Parentheses): Groups patterns together.

Below is a table summarizing these elements:

Let's apply these elements in practical examples using Python's re module:

  • Finding all instances of 'a' in a string:
  • Searching for any character between 'a' and 'z':
  • Matching any digit in a string:
  • Finding three consecutive digits:
  • Searching for words starting with 'S':
  • Matching a word at the beginning of a string:
  • Finding sequences of non-whitespace characters:
  • Replacing all digits with a hash (#):
  • Splitting a string by any whitespace:
  • Checking if a string ends with 'world':

These examples showcase the versatility and power of regular expressions in Python for various text processing tasks. By mastering the syntax and applying it through practical examples, you can leverage regular expressions to efficiently search, match, and manipulate strings in your Python projects.

Contribute with us!

Do not hesitate to contribute to Python tutorials on GitHub: create a fork, update content and issue a pull request.

Profile picture for user AliaksandrSumich

IMAGES

  1. Python3.8 Assignment expressions using ":="

    python 3 assignment expression

  2. Playing with Python 3.8 assignment expressions

    python 3 assignment expression

  3. What are Python Assignment Expressions and Using the Walrus Operator

    python 3 assignment expression

  4. The Walrus Operator: Python 3.8 Assignment Expressions

    python 3 assignment expression

  5. What is Python Assignment Operators? Full List With Types

    python 3 assignment expression

  6. Python 3 Tutorial

    python 3 assignment expression

VIDEO

  1. Python Lesson_11

  2. The Basics

  3. Python 3

  4. Python

  5. Python Operators

  6. Python statement and expression #python #coding #programming #reels

COMMENTS

  1. PEP 572

    28-Feb-2018 Python-Version: 3.8 Post-History: 28-Feb-2018, 02-Mar-2018, 23-Mar-2018, 04-Apr-2018, 17-Apr-2018, 25-Apr-2018, 09-Jul-2018, 05-Aug-2019 Resolution: Python-Dev message Table of Contents Abstract This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr.

  2. Assignment Expressions: The Walrus Operator

    Assignment expression are written with a new notation (:=) .This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side. Assignment expressions allow you to assign and return a value in the same expression.

  3. 6. Expressions

    This chapter explains the meaning of the elements of expressions in Python. Syntax Notes: In this and the following chapters, extended BNF notation will be used to describe syntax, not lexical analysis. When (one alternative of) a syntax rule has the form name ::= othername

  4. The Walrus Operator: Python 3.8 Assignment Expressions

    For Python 3.8, the biggest change is the addition of assignment expressions. Specifically, the := operator gives you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator. This tutorial is an in-depth introduction to the walrus operator.

  5. python

    What are assignment expressions (using the "walrus" or ":=" operator)? Why was this syntax added? Ask Question Asked 5 years, 9 months ago Modified 6 months ago Viewed 36k times 107 Since Python 3.8, code can use the so-called "walrus" operator ( := ), documented in PEP 572, for assignment expressions.

  6. Python's Assignment Operator: Write Robust Assignments

    Assignment Expressions With the Walrus Operator Managed Attribute Assignments Implicit Assignments in Python Define or Call a Function Work With Classes Import Modules and Objects Use a Decorator Access the Control Variable in a for Loop or a Comprehension Use the as Keyword Access the _ Special Variable in an Interactive Session

  7. How To Use Assignment Expressions in Python

    Python 3.8, released in October 2019, adds assignment expressions to Python via the := syntax. The assignment expression syntax is also sometimes called "the walrus operator" because := vaguely resembles a walrus with tusks. Assignment expressions allow variable assignments to occur inside of larger expressions.

  8. Operators and Expressions in Python

    Augmented Assignment Operators and Expressions Conclusion Remove ads In Python, operators are special symbols, combinations of symbols, or keywords that designate some type of computation. You can combine objects and operators to build expressions that perform the actual computation.

  9. 7. Simple statements

    An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. Assignment is defined recursively depending on the form of the target (list).

  10. New in Python 3.8: Assignment expressions

    As Python 3.8 gradually spreads into common usage, now might be a good time to look at one of the big changes it introduced, assignment expressions or the affectionately-nicknamed "walrus operator": while (block := f.read (256)) != '': process (block) That := is the new kid on the block. What you can do with this

  11. Python 101

    The general idea is that an assignment expression allows you to assign to variables within an expression. The syntax for doing this is: NAME := expr This operator has been called the "walrus operator", although their real name is "assignment expression". Interestingly, the CPython internals also refer to them as "named expressions".

  12. How To Use Assignment Expressions in Python

    Python 3.8 or above. Assignment expressions are a new feature added starting in Python 3.8. Using Assignment Expressions in if Statements. Let's start with an example of how you can use assignment expressions in an if statement. Consider the following code that checks the length of a list and prints a statement:

  13. Python walrus operator (Python 3.8 assignment expression)

    The "Python walrus operator", officially known as the assignment expression operator, was introduced in Python 3.8. It's symbolized by a colon followed by an equal sign :=. The Python community refers to it as the "walrus operator" due to its resemblance to a pair of eyes and tusks, like that of a walrus. Table of Contents hide.

  14. Python 3.8 Walrus Operator (Assignment Expression)

    The release of Python 3.8 came with an exciting new feature: the Walrus Operator. It's an assignment expression, or in simpler terms an assignment inside an expression. Python 3.8 Walrus Operator (Assignment Expression) Let's dive into practice immediately and look at the following code: users = [. {'name': 'Alice', 'uid': 123, 'approved ...

  15. 5. Assignment Expressions

    Despite being introduced in Python version 3.8, we can still view it as a relatively recent addition to the language. The assignment expressions have been discussed in PEP 572 and this is what was written about the naming: During discussion of this PEP, the operator became informally known as "the walrus operator".

  16. Python 3

    I recently came across PEP 572, which is a proposal for adding assignment expressions to Python 3.8 from Chris Angelico, Tim Peters and Guido van Rossum himself! I decided to check it out and see what an assignment expression was. The idea is actually quite simple. The Python core developers want a way to assign variables within an expression using the following notation:

  17. PEP 577

    The language grammar would be adjusted to allow augmented assignments to appear as expressions, where the result of the augmented assignment expression is the same post-calculation reference as is being bound to the given target. For example: >>> n = 0 >>> n += 5 5 >>> n -= 2 3 >>> n *= 3 9 >>> n 9. For mutable targets, this means the result is ...

  18. The brand new assignment expression of Python 3.8

    Python 3.8 introduces assignment expressions which lets us create new variables in places where we always wanted but never could in a usable way. Probably the best way to use this new feature is to create new variables in an if and use it in the scope of that block. For more information, you can read the specs here.

  19. Assignment Expressions

    It's called an assignment expression, and it allows you to save the return value of a function to a variable while at the same time…

  20. Assignment Expression Syntax

    Assignment Expression Syntax. For more information on concepts covered in this lesson, you can check out: Walrus operator syntax. One of the main reasons assignments were not expressions in Python from the beginning is the visual likeness of the assignment operator (=) and the equality comparison operator (==). This could potentially lead to bugs.

  21. python

    Python3.8 assignment expressions, use in list comprehension or as an expression 1 year, 3 months ago However, I'm not sure of the syntax to use for this particular function. Is there a way I could replace my usage of functools.reduce

  22. 9 Great Python Tricks That Increase the Elegance of Your Code

    2. Utilize the Walrus Operator for Assignment Expressions. Introduced in Python 3.8, the walrus operator, denoted by :=, allows you to assign values to variables within larger expressions. This operator derives its name from the resemblance of := to the eyes and tusks of a walrus. The walrus operator can significantly enhance the readability ...

  23. Concise syntax for attribute access and assignment: e.g., `self.(a, b

    In this proposal, I introduce a novel syntax aimed at simplifying multiple attribute access and assignment within objects. Motivation Class definitions often entail verbose patterns for initializing instance attributes, as exemplified below: class MyClass: def __init__(self, foo, bar, baz, qux): self.foo = foo self.bar = bar self.baz = baz self.qux = qux # Or equivalently class MyClass: def ...

  24. Concise syntax for attribute access and assignment: e.g., `obj.(a, b, c

    The proposed syntax also supports nested attribute access and assignment, allowing for complex expressions involving objects with deep attribute hierarchies: ... I believe it will affect the majority of existing Python programmers and will enhance their productivity in class design and many other tasks. Additionally, learning this new syntax ...

  25. Regular Expressions in Python: Basic Syntax

    Regular expressions (regex) are a powerful tool for pattern matching and data extraction in text processing. Python's re module provides a comprehensive set of functions to work with regular expressions. This article dives into the syntax of regular expressions in Python, accompanied by practical examples to help you grasp the concepts better.