The Ultimate Guide to Python’s Colon Operator – Everything You Need to Know

Introduction.

The Python colon operator is a critical component of the Python programming language that plays a crucial role in defining blocks of code, slicing sequences, and controlling flow. Understanding and mastering the colon operator is key to becoming proficient in Python programming. In this blog post, we will explore the various aspects of the colon operator, its usage, and best practices.

python colon before assignment

What is the colon operator?

The colon operator, represented by the ‘:’ symbol, is a fundamental feature of the Python language. It is primarily used to indicate the start of a code block or to separate the start and end indices in slicing operations. Let’s delve deeper into its definition, syntax, and its role in Python programming.

In Python, the colon operator is used in various contexts, including conditionals, loops, function and class definitions, and slicing and indexing sequences. It is important to note that the colon operator should not be confused with the assignment operator (=) or the comparison operator (==).

Its role in Python programming

The colon operator’s primary role is to define code blocks in Python. Code blocks are crucial for controlling the flow of a program, executing certain sections of code conditionally, and defining reusable sections of code in the form of functions and classes.

Additionally, the colon operator is used when working with sequences, such as lists, tuples, and strings, to extract specific elements or ranges of values. It provides a concise and powerful way to access and manipulate data within sequences.

Common misconceptions about the colon operator

Before we dive into the practical usage of the colon operator, let’s debunk some common misconceptions surrounding it. One misconception is the belief that the colon operator is limited to defining code blocks in Python. While this is a significant aspect of its usage, the colon operator also plays a crucial role in slicing and indexing sequences.

Another misconception is that the colon operator is only used with loops and conditional statements. While it is true that the colon operator is commonly used in these scenarios, its functionality extends far beyond them. Understanding all the applications of the colon operator is essential for unleashing the full power of Python.

Using the colon operator in Python

Indentation and code blocks.

In Python, code blocks are defined using indentation. The colon operator is used to indicate the start of a block and is followed by an indented block of code. Let’s explore different scenarios where the colon operator is used to define code blocks.

Creating conditional statements with if and else

The colon operator is used to define the code blocks associated with conditional statements such as if and else. Consider the following example:

Here, the colon operator is used after the condition, indicating that the subsequent indented block should be executed when the condition is satisfied. Similarly, the else clause also uses the colon operator to define its associated code block.

Implementing loops: for and while

The colon operator is also used in loops to indicate the start of the loop’s code block. Let’s see an example:

In the case of for loops, the colon operator is used after the iterable, indicating that the subsequent indented block should be executed for each item in the iterable. Similarly, the colon operator is used after the condition in while loops to define the associated code block.

Defining functions and classes

The colon operator is crucial when defining functions and classes in Python. It helps in separating the function or class signature from the subsequent code block. Here’s an example:

In both cases, the colon operator is used to indicate the start of the code block that belongs to the function or class. The indentation within the block is essential for maintaining the correct structure and scope.

Slicing and indexing with the colon operator

Aside from defining code blocks, the colon operator is extensively used for slicing and indexing sequences in Python, such as lists, tuples, and strings. Let’s explore the different ways we can use the colon operator in this context.

Accessing elements in lists and tuples

The colon operator is used to extract specific elements from lists and tuples. Consider the following example:

In this example, the colon operator is used to define the range of indices we want to extract from the list and tuple. The resulting selected_elements_list and selected_elements_tuple will contain the specified elements based on the index range.

Extracting substrings from strings

The colon operator can also be used to extract substrings from strings. Consider the following example:

In this case, the colon operator is used to define the range of indices representing the desired substring. The resulting substring will contain the characters from index 7 to index 11, inclusive.

Getting a range of values from sequences

The colon operator can also be used to obtain a range of values from sequences. This is particularly useful when working with numeric ranges. Consider the following example:

In this example, the colon operator is used to specify the range of values from the my_range sequence that we want to extract. The resulting selected_values will contain [3, 4, 5, 6, 7].

Advanced usage of the colon operator

Now that we have explored the basics of using the colon operator, let’s move on to more advanced usage scenarios. Understanding these advanced techniques will help you become even more proficient in Python programming.

Using step in slicing

In addition to specifying start and end indices, the colon operator also allows you to define a step value when slicing sequences. This enables you to extract elements with a certain interval. Let’s take a look at an example:

In this example, the step value of 2 instructs Python to extract every second element from the range starting at index 1 and ending at index 9. The resulting selected_elements will contain [2, 4, 6, 8]. This can be useful when you need to process or analyze specific subsets of a large sequence.

Combining slicing and indexing

The colon operator can be combined with indexing to extract specific elements from multidimensional sequences, such as multidimensional lists or arrays. Consider the following example:

In this example, the inner bracket with the index 1 selects the second row of the matrix. The subsequent bracket with the index 2 selects the third element of that row, resulting in the value 6. By chaining indexing and slicing operations, you can navigate and access elements within more complex data structures.

Applying the colon operator to multidimensional arrays

In addition to lists, tuples, and strings, the colon operator is used to slice and index multidimensional arrays, such as those provided by libraries like NumPy. These arrays can have more than two dimensions and can be sliced and indexed using the same principles we discussed earlier. Exploring multidimensional arrays is beyond the scope of this blog post, but mastering the colon operator will give you a solid foundation to work with these powerful data structures.

Best practices and tips for using the colon operator

Formatting and readability conventions.

When using the colon operator, it is important to follow consistent formatting and indentation conventions. This helps improve code readability and maintainability. Make sure to use consistent indentation, typically four spaces, after the colon operator to clearly define code blocks. Comments can be inserted within code blocks to provide additional context.

Additionally, when using the colon operator for slicing, ensure that you provide clear and concise indices to avoid confusion. Adding comments can be beneficial for explaining the purpose of the slicing operation.

Understanding when and where to use the colon operator

Mastering the usage of the colon operator involves understanding when and where to apply it in different situations. Familiarize yourself with the contexts where the colon operator is used, such as conditionals, loops, function and class definitions, and slicing operations. Practice with a variety of examples to reinforce your understanding.

Avoiding common mistakes and pitfalls

When working with the colon operator, you must be aware of common mistakes and pitfalls. One common mistake is forgetting to include the colon operator at the end of statements that require it, such as conditional statements, loop definitions, function, and class definitions. Always double-check that you have correctly included the colon operator to avoid syntax errors.

Another common mistake is mixing up the start and end indices when performing slicing operations. Ensure that you specify the correct indices to obtain the desired subset of a sequence. Regularly testing and debugging your code will help you identify and rectify any errors related to the colon operator.

In this blog post, we have explored the various aspects of the Python colon operator. We have seen its role in defining code blocks, slicing and indexing sequences, and its usage in advanced scenarios. Understanding and mastering the colon operator is essential for becoming proficient in Python programming.

By following the best practices and tips discussed, you will be able to use the colon operator effectively and avoid common mistakes. Remember, the colon operator is a powerful tool that allows you to control the flow of your program, extract specific elements from sequences, and work with multidimensional arrays.

Continue to practice and explore the colon operator in different contexts to further enhance your Python programming skills. With time and experience, you will become more confident in utilizing this essential operator to write clean, efficient, and robust Python code.

Related posts:

  • Mastering the Python Double Colon – A Comprehensive Guide for Developers
  • Mastering the Colon Operator in Python – A Comprehensive Guide
  • Mastering Double Colon in Java – A Comprehensive Guide for Programmers
  • Demystifying the Colon in Java – Understanding Its Purpose and Usage
  • Understanding Double Colon in Python – A Comprehensive Guide for Beginners

Why and when you need to use colon (:) in Python

by Nathan Sebhastian

Posted on May 30, 2023

Reading time: 2 minutes

python colon before assignment

In Python, the colon : symbol is used in many situations:

  • When you need to create an indented block
  • To slice a list or a string
  • Create a key:value pair in a dictionary object

This tutorial will show you when to use a colon in practice.

1. Creating an indented block

The colon symbol is commonly used in Python to create an indented block.

In Python, indents have a special meaning because they indicate that the code written in that line is a part of something.

That something can be a class, a function, a conditional, or a loop.

For example, you used the colon symbol when defining a class as follows:

If you only indent the lines below the class Car line, Python will respond with an syntax error expecting a colon.

The colon here works as the indicator marking the start of the class body.

The same also applies for functions, conditionals, and loops:

The code above shows when you need to use a colon to start an indented block.

2. To slice a list or a string

Colons are also used to slice a list or a string in Python.

The slicing syntax is as follows:

The three numbers marking the start , end , and step in a slice is separated using colons.

When you omit the other two parameters, you can use a double colon :: as follows:

Here, the colons are used to slice a string. You can also do the same with a list.

3. Create a key:value pair in a dictionary object

Another use of the colon symbol is to create a key:value pair in a dictionary object.

You use the curly brackets to start a dictionary object, then create the key:value pair using colons like this:

When you have more than one key:value pair, you need to separate them using a comma.

In other programming languages, you would see curly brackets used as the indicator of an indented block.

In Python, a colon is used to create an indented block, as well as for slicing a list or a string, and creating a key:value pair in a dictionary.

I hope this tutorial helps. See you in other tutorials!

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 8 – Style Guide for Python Code

Introduction, a foolish consistency is the hobgoblin of little minds, indentation, tabs or spaces, maximum line length, should a line break before or after a binary operator, blank lines, source file encoding, module level dunder names, string quotes, other recommendations, when to use trailing commas, block comments, inline comments, documentation strings, overriding principle, descriptive: naming styles, names to avoid, ascii compatibility, package and module names, class names, type variable names, exception names, global variable names, function and variable names, function and method arguments, method names and instance variables, designing for inheritance, public and internal interfaces, function annotations, variable annotations.

This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python .

This document and PEP 257 (Docstring Conventions) were adapted from Guido’s original Python Style Guide essay, with some additions from Barry’s style guide [2] .

This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in the language itself.

Many projects have their own coding style guidelines. In the event of any conflicts, such project-specific guides take precedence for that project.

One of Guido’s key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, “Readability counts”.

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

However, know when to be inconsistent – sometimes style guide recommendations just aren’t applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don’t hesitate to ask!

In particular: do not break backwards compatibility just to comply with this PEP!

Some other good reasons to ignore a particular guideline:

  • When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
  • To be consistent with surrounding code that also breaks it (maybe for historic reasons) – although this is also an opportunity to clean up someone else’s mess (in true XP style).
  • Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.
  • When the code needs to remain compatible with older versions of Python that don’t support the feature recommended by the style guide.

Code Lay-out

Use 4 spaces per indentation level.

Continuation lines should align wrapped elements either vertically using Python’s implicit line joining inside parentheses, brackets and braces, or using a hanging indent [1] . When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line:

The 4-space rule is optional for continuation lines.

When the conditional part of an if -statement is long enough to require that it be written across multiple lines, it’s worth noting that the combination of a two character keyword (i.e. if ), plus a single space, plus an opening parenthesis creates a natural 4-space indent for the subsequent lines of the multiline conditional. This can produce a visual conflict with the indented suite of code nested inside the if -statement, which would also naturally be indented to 4 spaces. This PEP takes no explicit position on how (or whether) to further visually distinguish such conditional lines from the nested suite inside the if -statement. Acceptable options in this situation include, but are not limited to:

(Also see the discussion of whether to break before or after binary operators below.)

The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character of the last line of list, as in:

or it may be lined up under the first character of the line that starts the multiline construct, as in:

Spaces are the preferred indentation method.

Tabs should be used solely to remain consistent with code that is already indented with tabs.

Python disallows mixing tabs and spaces for indentation.

Limit all lines to a maximum of 79 characters.

For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.

Limiting the required editor window width makes it possible to have several files open side by side, and works well when using code review tools that present the two versions in adjacent columns.

The default wrapping in most tools disrupts the visual structure of the code, making it more difficult to understand. The limits are chosen to avoid wrapping in editors with the window width set to 80, even if the tool places a marker glyph in the final column when wrapping lines. Some web based tools may not offer dynamic line wrapping at all.

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 99 characters, provided that comments and docstrings are still wrapped at 72 characters.

The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72).

The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

Backslashes may still be appropriate at times. For example, long, multiple with -statements could not use implicit continuation before Python 3.10, so backslashes were acceptable for that case:

(See the previous discussion on multiline if-statements for further thoughts on the indentation of such multiline with -statements.)

Another such case is with assert statements.

Make sure to indent the continued line appropriately.

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line. Here, the eye has to do extra work to tell which items are added and which are subtracted:

To solve this readability problem, mathematicians and their publishers follow the opposite convention. Donald Knuth explains the traditional rule in his Computers and Typesetting series: “Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations” [3] .

Following the tradition from mathematics usually results in more readable code:

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth’s style is suggested.

Surround top-level function and class definitions with two blank lines.

Method definitions inside a class are surrounded by a single blank line.

Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

Use blank lines in functions, sparingly, to indicate logical sections.

Python accepts the control-L (i.e. ^L) form feed character as whitespace; many tools treat these characters as page separators, so you may use them to separate pages of related sections of your file. Note, some editors and web-based code viewers may not recognize control-L as a form feed and will show another glyph in its place.

Code in the core Python distribution should always use UTF-8, and should not have an encoding declaration.

In the standard library, non-UTF-8 encodings should be used only for test purposes. Use non-ASCII characters sparingly, preferably only to denote places and human names. If using non-ASCII characters as data, avoid noisy Unicode characters like z̯̯͡a̧͎̺l̡͓̫g̹̲o̡̼̘ and byte order marks.

All identifiers in the Python standard library MUST use ASCII-only identifiers, and SHOULD use English words wherever feasible (in many cases, abbreviations and technical terms are used which aren’t English).

Open source projects with a global audience are encouraged to adopt a similar policy.

It’s okay to say this though:

Imports should be grouped in the following order:

  • Standard library imports.
  • Related third party imports.
  • Local application/library specific imports.

You should put a blank line between each group of imports.

However, explicit relative imports are an acceptable alternative to absolute imports, especially when dealing with complex package layouts where using absolute imports would be unnecessarily verbose:

Standard library code should avoid complex package layouts and always use absolute imports.

If this spelling causes local name clashes, then spell them explicitly:

and use myclass.MyClass and foo.bar.yourclass.YourClass .

When republishing names this way, the guidelines below regarding public and internal interfaces still apply.

Module level “dunders” (i.e. names with two leading and two trailing underscores) such as __all__ , __author__ , __version__ , etc. should be placed after the module docstring but before any import statements except from __future__ imports. Python mandates that future-imports must appear in the module before any other code except docstrings:

In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257 .

Whitespace in Expressions and Statements

Avoid extraneous whitespace in the following situations:

  • Immediately inside parentheses, brackets or braces: # Correct: spam ( ham [ 1 ], { eggs : 2 }) # Wrong: spam ( ham [ 1 ], { eggs : 2 } )
  • Between a trailing comma and a following close parenthesis: # Correct: foo = ( 0 ,) # Wrong: bar = ( 0 , )
  • Immediately before a comma, semicolon, or colon: # Correct: if x == 4 : print ( x , y ); x , y = y , x # Wrong: if x == 4 : print ( x , y ) ; x , y = y , x
  • However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted, the space is omitted: # Correct: ham [ 1 : 9 ], ham [ 1 : 9 : 3 ], ham [: 9 : 3 ], ham [ 1 :: 3 ], ham [ 1 : 9 :] ham [ lower : upper ], ham [ lower : upper :], ham [ lower :: step ] ham [ lower + offset : upper + offset ] ham [: upper_fn ( x ) : step_fn ( x )], ham [:: step_fn ( x )] ham [ lower + offset : upper + offset ] # Wrong: ham [ lower + offset : upper + offset ] ham [ 1 : 9 ], ham [ 1 : 9 ], ham [ 1 : 9 : 3 ] ham [ lower : : step ] ham [ : upper ]
  • Immediately before the open parenthesis that starts the argument list of a function call: # Correct: spam ( 1 ) # Wrong: spam ( 1 )
  • Immediately before the open parenthesis that starts an indexing or slicing: # Correct: dct [ 'key' ] = lst [ index ] # Wrong: dct [ 'key' ] = lst [ index ]
  • More than one space around an assignment (or other) operator to align it with another: # Correct: x = 1 y = 2 long_variable = 3 # Wrong: x = 1 y = 2 long_variable = 3
  • Avoid trailing whitespace anywhere. Because it’s usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker. Some editors don’t preserve it and many projects (like CPython itself) have pre-commit hooks that reject it.
  • Always surround these binary operators with a single space on either side: assignment ( = ), augmented assignment ( += , -= etc.), comparisons ( == , < , > , != , <> , <= , >= , in , not in , is , is not ), Booleans ( and , or , not ).
  • If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator: # Correct: i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = ( a + b ) * ( a - b ) # Wrong: i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = ( a + b ) * ( a - b )
  • Function annotations should use the normal rules for colons and always have spaces around the -> arrow if present. (See Function Annotations below for more about function annotations.): # Correct: def munge ( input : AnyStr ): ... def munge () -> PosInt : ... # Wrong: def munge ( input : AnyStr ): ... def munge () -> PosInt : ...

When combining an argument annotation with a default value, however, do use spaces around the = sign:

Rather not:

Definitely not:

Trailing commas are usually optional, except they are mandatory when making a tuple of one element. For clarity, it is recommended to surround the latter in (technically redundant) parentheses:

When trailing commas are redundant, they are often helpful when a version control system is used, when a list of values, arguments or imported items is expected to be extended over time. The pattern is to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line. However it does not make sense to have a trailing comma on the same line as the closing delimiter (except in the above case of singleton tuples):

Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!

Comments should be complete sentences. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).

Block comments generally consist of one or more paragraphs built out of complete sentences, with each sentence ending in a period.

You should use one or two spaces after a sentence-ending period in multi-sentence comments, except after the final sentence.

Ensure that your comments are clear and easily understandable to other speakers of the language you are writing in.

Python coders from non-English speaking countries: please write your comments in English, unless you are 120% sure that the code will never be read by people who don’t speak your language.

Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).

Paragraphs inside a block comment are separated by a line containing a single # .

Use inline comments sparingly.

An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.

Inline comments are unnecessary and in fact distracting if they state the obvious. Don’t do this:

But sometimes, this is useful:

Conventions for writing good documentation strings (a.k.a. “docstrings”) are immortalized in PEP 257 .

  • Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line.
  • PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself: """Return a foobang Optional plotz says to frobnicate the bizbaz first. """
  • For one liner docstrings, please keep the closing """ on the same line: """Return an ex-parrot."""

Naming Conventions

The naming conventions of Python’s library are a bit of a mess, so we’ll never get this completely consistent – nevertheless, here are the currently recommended naming standards. New modules and packages (including third party frameworks) should be written to these standards, but where an existing library has a different style, internal consistency is preferred.

Names that are visible to the user as public parts of the API should follow conventions that reflect usage rather than implementation.

There are a lot of different naming styles. It helps to be able to recognize what naming style is being used, independently from what they are used for.

The following naming styles are commonly distinguished:

  • b (single lowercase letter)
  • B (single uppercase letter)
  • lower_case_with_underscores
  • UPPER_CASE_WITH_UNDERSCORES

Note: When using acronyms in CapWords, capitalize all the letters of the acronym. Thus HTTPServerError is better than HttpServerError.

  • mixedCase (differs from CapitalizedWords by initial lowercase character!)
  • Capitalized_Words_With_Underscores (ugly!)

There’s also the style of using a short unique prefix to group related names together. This is not used much in Python, but it is mentioned for completeness. For example, the os.stat() function returns a tuple whose items traditionally have names like st_mode , st_size , st_mtime and so on. (This is done to emphasize the correspondence with the fields of the POSIX system call struct, which helps programmers familiar with that.)

The X11 library uses a leading X for all its public functions. In Python, this style is generally deemed unnecessary because attribute and method names are prefixed with an object, and function names are prefixed with a module name.

In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore : weak “internal use” indicator. E.g. from M import * does not import objects whose names start with an underscore.
  • single_trailing_underscore_ : used by convention to avoid conflicts with Python keyword, e.g. : tkinter . Toplevel ( master , class_ = 'ClassName' )
  • __double_leading_underscore : when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo ; see below).
  • __double_leading_and_trailing_underscore__ : “magic” objects or attributes that live in user-controlled namespaces. E.g. __init__ , __import__ or __file__ . Never invent such names; only use them as documented.

Prescriptive: Naming Conventions

Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names.

In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use ‘l’, use ‘L’ instead.

Identifiers used in the standard library must be ASCII compatible as described in the policy section of PEP 3131 .

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket ).

Class names should normally use the CapWords convention.

The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable.

Note that there is a separate convention for builtin names: most builtin names are single words (or two words run together), with the CapWords convention used only for exception names and builtin constants.

Names of type variables introduced in PEP 484 should normally use CapWords preferring short names: T , AnyStr , Num . It is recommended to add suffixes _co or _contra to the variables used to declare covariant or contravariant behavior correspondingly:

Because exceptions should be classes, the class naming convention applies here. However, you should use the suffix “Error” on your exception names (if the exception actually is an error).

(Let’s hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.

Modules that are designed for use via from M import * should use the __all__ mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are “module non-public”).

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

Variable names follow the same convention as function names.

mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility.

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

If a function argument’s name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is better than clss . (Perhaps better is to avoid such clashes by using a synonym.)

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

Use one leading underscore only for non-public methods and instance variables.

To avoid name clashes with subclasses, use two leading underscores to invoke Python’s name mangling rules.

Python mangles these names with the class name: if class Foo has an attribute named __a , it cannot be accessed by Foo.__a . (An insistent user could still gain access by calling Foo._Foo__a .) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.

Note: there is some controversy about the use of __names (see below).

Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL .

Always decide whether a class’s methods and instance variables (collectively: “attributes”) should be public or non-public. If in doubt, choose non-public; it’s easier to make it public later than to make a public attribute non-public.

Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backwards incompatible changes. Non-public attributes are those that are not intended to be used by third parties; you make no guarantees that non-public attributes won’t change or even be removed.

We don’t use the term “private” here, since no attribute is really private in Python (without a generally unnecessary amount of work).

Another category of attributes are those that are part of the “subclass API” (often called “protected” in other languages). Some classes are designed to be inherited from, either to extend or modify aspects of the class’s behavior. When designing such a class, take care to make explicit decisions about which attributes are public, which are part of the subclass API, and which are truly only to be used by your base class.

With this in mind, here are the Pythonic guidelines:

  • Public attributes should have no leading underscores.

Note 1: See the argument name recommendation above for class methods.

Note 1: Try to keep the functional behavior side-effect free, although side-effects such as caching are generally fine.

Note 2: Avoid using properties for computationally expensive operations; the attribute notation makes the caller believe that access is (relatively) cheap.

Note 1: Note that only the simple class name is used in the mangled name, so if a subclass chooses both the same class name and attribute name, you can still get name collisions.

Note 2: Name mangling can make certain uses, such as debugging and __getattr__() , less convenient. However the name mangling algorithm is well documented and easy to perform manually.

Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.

Any backwards compatibility guarantees apply only to public interfaces. Accordingly, it is important that users be able to clearly distinguish between public and internal interfaces.

Documented interfaces are considered public, unless the documentation explicitly declares them to be provisional or internal interfaces exempt from the usual backwards compatibility guarantees. All undocumented interfaces should be assumed to be internal.

To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute. Setting __all__ to an empty list indicates that the module has no public API.

Even with __all__ set appropriately, internal interfaces (packages, modules, classes, functions, attributes or other names) should still be prefixed with a single leading underscore.

An interface is also considered internal if any containing namespace (package, module or class) is considered internal.

Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module’s API, such as os.path or a package’s __init__ module that exposes functionality from submodules.

Programming Recommendations

For example, do not rely on CPython’s efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn’t present at all in implementations that don’t use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

Also, beware of writing if x when you really mean if x is not None – e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

  • Use is not operator rather than not ... is . While both expressions are functionally identical, the former is more readable and preferred: # Correct: if foo is not None : # Wrong: if not foo is None :

To minimize the effort involved, the functools.total_ordering() decorator provides a tool to generate missing comparison methods.

PEP 207 indicates that reflexivity rules are assumed by Python. Thus, the interpreter may swap y > x with x < y , y >= x with x <= y , and may swap the arguments of x == y and x != y . The sort() and min() operations are guaranteed to use the < operator and the max() function uses the > operator. However, it is best to implement all six operations so that confusion doesn’t arise in other contexts.

The first form means that the name of the resulting function object is specifically ‘f’ instead of the generic ‘<lambda>’. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

Design exception hierarchies based on the distinctions that code catching the exceptions is likely to need, rather than the locations where the exceptions are raised. Aim to answer the question “What went wrong?” programmatically, rather than only stating that “A problem occurred” (see PEP 3151 for an example of this lesson being learned for the builtin exception hierarchy)

Class naming conventions apply here, although you should add the suffix “Error” to your exception classes if the exception is an error. Non-error exceptions that are used for non-local flow control or other forms of signaling need no special suffix.

When deliberately replacing an inner exception (using raise X from None ), ensure that relevant details are transferred to the new exception (such as preserving the attribute name when converting KeyError to AttributeError, or embedding the text of the original exception in the new exception message).

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException: ).

A good rule of thumb is to limit use of bare ‘except’ clauses to two cases:

  • If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
  • If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise . try...finally can be a better way to handle this case.
  • When catching operating system errors, prefer the explicit exception hierarchy introduced in Python 3.3 over introspection of errno values.
  • Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs: # Correct: try : value = collection [ key ] except KeyError : return key_not_found ( key ) else : return handle_value ( value ) # Wrong: try : # Too broad! return handle_value ( collection [ key ]) except KeyError : # Will also catch KeyError raised by handle_value() return key_not_found ( key )
  • When a resource is local to a particular section of code, use a with statement to ensure it is cleaned up promptly and reliably after use. A try/finally statement is also acceptable.

The latter example doesn’t provide any information to indicate that the __enter__ and __exit__ methods are doing something other than closing the connection after a transaction. Being explicit is important in this case.

  • Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None , and an explicit return statement should be present at the end of the function (if reachable): # Correct: def foo ( x ): if x >= 0 : return math . sqrt ( x ) else : return None def bar ( x ): if x < 0 : return None return math . sqrt ( x ) # Wrong: def foo ( x ): if x >= 0 : return math . sqrt ( x ) def bar ( x ): if x < 0 : return return math . sqrt ( x )

startswith() and endswith() are cleaner and less error prone:

  • Object type comparisons should always use isinstance() instead of comparing types directly: # Correct: if isinstance ( obj , int ): # Wrong: if type ( obj ) is type ( 1 ):
  • For sequences, (strings, lists, tuples), use the fact that empty sequences are false: # Correct: if not seq : if seq : # Wrong: if len ( seq ): if not len ( seq ):
  • Don’t write string literals that rely on significant trailing whitespace. Such trailing whitespace is visually indistinguishable and some editors (or more recently, reindent.py) will trim them.
  • Use of the flow control statements return / break / continue within the finally suite of a try...finally , where the flow control statement would jump outside the finally suite, is discouraged. This is because such statements will implicitly cancel any active exception that is propagating through the finally suite: # Wrong: def foo (): try : 1 / 0 finally : return 42

With the acceptance of PEP 484 , the style rules for function annotations have changed.

  • Function annotations should use PEP 484 syntax (there are some formatting recommendations for annotations in the previous section).
  • The experimentation with annotation styles that was recommended previously in this PEP is no longer encouraged.
  • However, outside the stdlib, experiments within the rules of PEP 484 are now encouraged. For example, marking up a large third party library or application with PEP 484 style type annotations, reviewing how easy it was to add those annotations, and observing whether their presence increases code understandability.
  • The Python standard library should be conservative in adopting such annotations, but their use is allowed for new code and for big refactorings.

near the top of the file; this tells type checkers to ignore all annotations. (More fine-grained ways of disabling complaints from type checkers can be found in PEP 484 .)

  • Like linters, type checkers are optional, separate tools. Python interpreters by default should not issue any messages due to type checking and should not alter their behavior based on annotations.
  • Users who don’t want to use type checkers are free to ignore them. However, it is expected that users of third party library packages may want to run type checkers over those packages. For this purpose PEP 484 recommends the use of stub files: .pyi files that are read by the type checker in preference of the corresponding .py files. Stub files can be distributed with a library, or separately (with the library author’s permission) through the typeshed repo [5] .

PEP 526 introduced variable annotations. The style recommendations for them are similar to those on function annotations described above:

  • Annotations for module level variables, class and instance variables, and local variables should have a single space after the colon.
  • There should be no space before the colon.
  • If an assignment has a right hand side, then the equality sign should have exactly one space on both sides: # Correct: code : int class Point : coords : Tuple [ int , int ] label : str = '<unknown>' # Wrong: code : int # No space after colon code : int # Space before colon class Test : result : int = 0 # No spaces around equality sign
  • Although the PEP 526 is accepted for Python 3.6, the variable annotation syntax is the preferred syntax for stub files on all versions of Python (see PEP 484 for details).

This document has been placed in the public domain.

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

Last modified: 2023-12-09 16:19:37 GMT

Script Everything

What Does Colon Equals Mean In Python? The New Walrus Operator :=

python colon before assignment

In Python 3.8 a new assignment expression hit allowing for easier access of variables that are used when being assigned. Here are some tips on how this can be used in your everyday coding.

Wait, what’s an assignment expression ?

You may have heard of the term assignment operator and seen its use in the wild when doing things like incrementing a variable by 1 in Python . This is where an operator, like + or - is combined with the assignment key = . For example, x += 1 which means I’m adding the value of 1 to the variable x .

So an assignment operator performs an operation and assigns the change to the variable used. Therefore, an assignment expression is where a variable is assigned the result of something, maybe the result from a function.

But how is that different to a normal assignment?

The difference with the new walrus operator is that this assignment can occur where would otherwise be an expression. For example, in an if statement we have an expression where a comparison is performed. What if in the expression there was an assignment to a variable such that the variable can be used elsewhere in the code?

Take this simple example which I frequently use when scraping websites using Beautiful Soup library and checking if an element exists on the page:

Throughout this website you’ve seen copious examples in the Python REPL where to evaluate an expression I have used the following type of structure (for example when teaching on how to print a list ):

Notice how in the two outputs of the array above I needed to prompt the REPL to output the result on its own line. For example, the command print(my_list) prompted to print the result of the variable labelled my_list to the console window. So too did the line where the variable was the only element on the line.

So what does this new funny looking and named operator actually do?

Instead of using these types of prompts (i.e. print or the variable name) to see the result of what is stored in a variable without writing a separate line for the output now the walrus operator can be used, like so:

Notice that a couple of changes are needed to the code to output the result to the console. Firstly the entire assignment needs to be wrapped in parentheses, otherwise a SyntaxError results, as shown here:

Secondly, the assignment equal sign needs to be prefixed with a colon.

So can see you see why they call it the walrus operator ? (:=)

How Can This Be Useful?

Besides needing fewer lines and code to output a result to the REPL console it could also be very helpful when needing to operate on a result from a function, especially if the result from the function is to be used in the immediate context.

Recently I found myself using the walrus operator when reading data from a file into a list. My process before using the walrus operator was to capture each line, perform an operation on the line being read, and then either print the line or do something with it like inserting the line into a list.

Here is a portion of my original code where I was seeing if a line from a file contained any numerical digits and if it did to print the result:

Using the walrus operator on this simple code reduces it to the following:

As you can see by comparing the above code with the previous code the two lines where the variable digits captured the result from re.findall() and is checked against the if statement both of those lines are compressed into one.

This enables leaner code and is relatively easy for the user to understand what is happening.

The walrus operator is a new assignment operator introduced in Python 3.8 that can enable leaner code by assigning the value of a variable that can be used elsewhere in your code. This can save having to declare the result of the assignment elsewhere in your code as demonstrated above with the regular expression code.

Photo of author

python colon before assignment

Explore your training options in 10 minutes Get Started

  • Graduate Stories
  • Partner Spotlights
  • Bootcamp Prep
  • Bootcamp Admissions
  • University Bootcamps
  • Coding Tools
  • Software Engineering
  • Web Development
  • Data Science
  • Tech Guides
  • Tech Resources
  • Career Advice
  • Online Learning
  • Internships
  • Apprenticeships
  • Tech Salaries
  • Associate Degree
  • Bachelor's Degree
  • Master's Degree
  • University Admissions
  • Best Schools
  • Certifications
  • Bootcamp Financing
  • Higher Ed Financing
  • Scholarships
  • Financial Aid
  • Best Coding Bootcamps
  • Best Online Bootcamps
  • Best Web Design Bootcamps
  • Best Data Science Bootcamps
  • Best Technology Sales Bootcamps
  • Best Data Analytics Bootcamps
  • Best Cybersecurity Bootcamps
  • Best Digital Marketing Bootcamps
  • Los Angeles
  • San Francisco
  • Browse All Locations
  • Digital Marketing
  • Machine Learning
  • See All Subjects
  • Bootcamps 101
  • Full-Stack Development
  • Career Changes
  • View all Career Discussions
  • Mobile App Development
  • Cybersecurity
  • Product Management
  • UX/UI Design
  • What is a Coding Bootcamp?
  • Are Coding Bootcamps Worth It?
  • How to Choose a Coding Bootcamp
  • Best Online Coding Bootcamps and Courses
  • Best Free Bootcamps and Coding Training
  • Coding Bootcamp vs. Community College
  • Coding Bootcamp vs. Self-Learning
  • Bootcamps vs. Certifications: Compared
  • What Is a Coding Bootcamp Job Guarantee?
  • How to Pay for Coding Bootcamp
  • Ultimate Guide to Coding Bootcamp Loans
  • Best Coding Bootcamp Scholarships and Grants
  • Education Stipends for Coding Bootcamps
  • Get Your Coding Bootcamp Sponsored by Your Employer
  • GI Bill and Coding Bootcamps
  • Tech Intevriews
  • Our Enterprise Solution
  • Connect With Us
  • Publication
  • Reskill America
  • Partner With Us

Career Karma

  • Resource Center
  • Bachelor’s Degree
  • Master’s Degree

Python local variable referenced before assignment Solution

When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. This error is raised when you try to use a variable before it has been assigned in the local context .

In this guide, we talk about what this error means and why it is raised. We walk through an example of this error in action to help you understand how you can solve it.

Find your bootcamp match

What is unboundlocalerror: local variable referenced before assignment.

Trying to assign a value to a variable that does not have local scope can result in this error:

Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function , that variable is local. This is because it is assumed that when you define a variable inside a function you only need to access it inside that function.

There are two variable scopes in Python: local and global. Global variables are accessible throughout an entire program; local variables are only accessible within the function in which they are originally defined.

Let’s take a look at how to solve this error.

An Example Scenario

We’re going to write a program that calculates the grade a student has earned in class.

We start by declaring two variables:

These variables store the numerical and letter grades a student has earned, respectively. By default, the value of “letter” is “F”. Next, we write a function that calculates a student’s letter grade based on their numerical grade using an “if” statement :

Finally, we call our function:

This line of code prints out the value returned by the calculate_grade() function to the console. We pass through one parameter into our function: numerical. This is the numerical value of the grade a student has earned.

Let’s run our code and see what happens:

An error has been raised.

The Solution

Our code returns an error because we reference “letter” before we assign it.

We have set the value of “numerical” to 42. Our if statement does not set a value for any grade over 50. This means that when we call our calculate_grade() function, our return statement does not know the value to which we are referring.

We do define “letter” at the start of our program. However, we define it in the global context. Python treats “return letter” as trying to return a local variable called “letter”, not a global variable.

We solve this problem in two ways. First, we can add an else statement to our code. This ensures we declare “letter” before we try to return it:

Let’s try to run our code again:

Our code successfully prints out the student’s grade.

If you are using an “if” statement where you declare a variable, you should make sure there is an “else” statement in place. This will make sure that even if none of your if statements evaluate to True, you can still set a value for the variable with which you are going to work.

Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our calculate_grade() function. However, this approach is likely to lead to more confusing code and other issues. In general, variables should not be declared using “global” unless absolutely necessary . Your first, and main, port of call should always be to make sure that a variable is correctly defined.

In the example above, for instance, we did not check that the variable “letter” was defined in all use cases.

That’s it! We have fixed the local variable error in our code.

The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.

Now you’re ready to solve UnboundLocalError Python errors like a professional developer !

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .

What's Next?

icon_10

Get matched with top bootcamps

Ask a question to our community, take our careers quiz.

James Gallagher

Leave a Reply Cancel reply

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

Apply to top tech training programs in one click

  • Python »
  • 3.12.3 Documentation »
  • The Python Language Reference »
  • 8. Compound statements
  • Theme Auto Light Dark |

8. Compound statements ¶

Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line.

The if , while and for statements implement traditional control flow constructs. try specifies exception handlers and/or cleanup code for a group of statements, while the with statement allows the execution of initialization and finalization code around a block of code. Function and class definitions are also syntactically compound statements.

A compound statement consists of one or more ‘clauses.’ A clause consists of a header and a ‘suite.’ The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. Only the latter form of a suite can contain nested compound statements; the following is illegal, mostly because it wouldn’t be clear to which if clause a following else clause would belong:

Also note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the print() calls are executed:

Summarizing:

Note that statements always end in a NEWLINE possibly followed by a DEDENT . Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the ‘dangling else ’ problem is solved in Python by requiring nested if statements to be indented).

The formatting of the grammar rules in the following sections places each clause on a separate line for clarity.

8.1. The if statement ¶

The if statement is used for conditional execution:

It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section Boolean operations for the definition of true and false); then that suite is executed (and no other part of the if statement is executed or evaluated). If all expressions are false, the suite of the else clause, if present, is executed.

8.2. The while statement ¶

The while statement is used for repeated execution as long as an expression is true:

This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

8.3. The for statement ¶

The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:

The starred_list expression is evaluated once; it should yield an iterable object. An iterator is created for that iterable. The first item provided by the iterator is then assigned to the target list using the standard rules for assignments (see Assignment statements ), and the suite is executed. This repeats for each item provided by the iterator. When the iterator is exhausted, the suite in the else clause, if present, is executed, and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there is no next item.

The for-loop makes assignments to the variables in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop:

Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop. Hint: the built-in type range() represents immutable arithmetic sequences of integers. For instance, iterating range(3) successively yields 0, 1, and then 2.

Changed in version 3.11: Starred elements are now allowed in the expression list.

8.4. The try statement ¶

The try statement specifies exception handlers and/or cleanup code for a group of statements:

Additional information on exceptions can be found in section Exceptions , and information on using the raise statement to generate exceptions may be found in section The raise statement .

8.4.1. except clause ¶

The except clause(s) specify one or more exception handlers. When no exception occurs in the try clause, no exception handler is executed. When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if the object is the class or a non-virtual base class of the exception object, or a tuple containing an item that is the class or a non-virtual base class of the exception object.

If no except clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack. [ 1 ]

If the evaluation of an expression in the header of an except clause raises an exception, the original search for a handler is canceled and a search starts for the new exception in the surrounding code and on the call stack (it is treated as if the entire try statement raised the exception).

When a matching except clause is found, the exception is assigned to the target specified after the as keyword in that except clause, if present, and the except clause’s suite is executed. All except clauses must have an executable block. When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)

When an exception has been assigned using as target , it is cleared at the end of the except clause. This is as if

was translated to

This means the exception must be assigned to a different name to be able to refer to it after the except clause. Exceptions are cleared because with the traceback attached to them, they form a reference cycle with the stack frame, keeping all locals in that frame alive until the next garbage collection occurs.

Before an except clause’s suite is executed, the exception is stored in the sys module, where it can be accessed from within the body of the except clause by calling sys.exception() . When leaving an exception handler, the exception stored in the sys module is reset to its previous value:

8.4.2. except* clause ¶

The except* clause(s) are used for handling ExceptionGroup s. The exception type for matching is interpreted as in the case of except , but in the case of exception groups we can have partial matches when the type matches some of the exceptions in the group. This means that multiple except* clauses can execute, each handling part of the exception group. Each clause executes at most once and handles an exception group of all matching exceptions. Each exception in the group is handled by at most one except* clause, the first that matches it.

Any remaining exceptions that were not handled by any except* clause are re-raised at the end, along with all exceptions that were raised from within the except* clauses. If this list contains more than one exception to reraise, they are combined into an exception group.

If the raised exception is not an exception group and its type matches one of the except* clauses, it is caught and wrapped by an exception group with an empty message string.

An except* clause must have a matching type, and this type cannot be a subclass of BaseExceptionGroup . It is not possible to mix except and except* in the same try . break , continue and return cannot appear in an except* clause.

8.4.3. else clause ¶

The optional else clause is executed if the control flow leaves the try suite, no exception was raised, and no return , continue , or break statement was executed. Exceptions in the else clause are not handled by the preceding except clauses.

8.4.4. finally clause ¶

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return , break or continue statement, the saved exception is discarded:

The exception information is not available to the program during execution of the finally clause.

When a return , break or continue statement is executed in the try suite of a try … finally statement, the finally clause is also executed ‘on the way out.’

The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:

Changed in version 3.8: Prior to Python 3.8, a continue statement was illegal in the finally clause due to a problem with the implementation.

8.5. The with statement ¶

The with statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers ). This allows common try … except … finally usage patterns to be encapsulated for convenient reuse.

The execution of the with statement with one “item” proceeds as follows:

The context expression (the expression given in the with_item ) is evaluated to obtain a context manager.

The context manager’s __enter__() is loaded for later use.

The context manager’s __exit__() is loaded for later use.

The context manager’s __enter__() method is invoked.

If a target was included in the with statement, the return value from __enter__() is assigned to it.

The with statement guarantees that if the __enter__() method returns without an error, then __exit__() will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 7 below.

The suite is executed.

The context manager’s __exit__() method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to __exit__() . Otherwise, three None arguments are supplied.

If the suite was exited due to an exception, and the return value from the __exit__() method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the with statement.

If the suite was exited for any reason other than an exception, the return value from __exit__() is ignored, and execution proceeds at the normal location for the kind of exit that was taken.

The following code:

is semantically equivalent to:

With more than one item, the context managers are processed as if multiple with statements were nested:

You can also write multi-item context managers in multiple lines if the items are surrounded by parentheses. For example:

Changed in version 3.1: Support for multiple context expressions.

Changed in version 3.10: Support for using grouping parentheses to break the statement in multiple lines.

The specification, background, and examples for the Python with statement.

8.6. The match statement ¶

Added in version 3.10.

The match statement is used for pattern matching. Syntax:

This section uses single quotes to denote soft keywords .

Pattern matching takes a pattern as input (following case ) and a subject value (following match ). The pattern (which may contain subpatterns) is matched against the subject value. The outcomes are:

A match success or failure (also termed a pattern success or failure).

Possible binding of matched values to a name. The prerequisites for this are further discussed below.

The match and case keywords are soft keywords .

PEP 634 – Structural Pattern Matching: Specification

PEP 636 – Structural Pattern Matching: Tutorial

8.6.1. Overview ¶

Here’s an overview of the logical flow of a match statement:

The subject expression subject_expr is evaluated and a resulting subject value obtained. If the subject expression contains a comma, a tuple is constructed using the standard rules .

Each pattern in a case_block is attempted to match with the subject value. The specific rules for success or failure are described below. The match attempt can also bind some or all of the standalone names within the pattern. The precise pattern binding rules vary per pattern type and are specified below. Name bindings made during a successful pattern match outlive the executed block and can be used after the match statement .

During failed pattern matches, some subpatterns may succeed. Do not rely on bindings being made for a failed match. Conversely, do not rely on variables remaining unchanged after a failed match. The exact behavior is dependent on implementation and may vary. This is an intentional decision made to allow different implementations to add optimizations.

If the pattern succeeds, the corresponding guard (if present) is evaluated. In this case all name bindings are guaranteed to have happened.

If the guard evaluates as true or is missing, the block inside case_block is executed.

Otherwise, the next case_block is attempted as described above.

If there are no further case blocks, the match statement is completed.

Users should generally never rely on a pattern being evaluated. Depending on implementation, the interpreter may cache values or use other optimizations which skip repeated evaluations.

A sample match statement:

In this case, if flag is a guard. Read more about that in the next section.

8.6.2. Guards ¶

A guard (which is part of the case ) must succeed for code inside the case block to execute. It takes the form: if followed by an expression.

The logical flow of a case block with a guard follows:

Check that the pattern in the case block succeeded. If the pattern failed, the guard is not evaluated and the next case block is checked.

If the pattern succeeded, evaluate the guard .

If the guard condition evaluates as true, the case block is selected.

If the guard condition evaluates as false, the case block is not selected.

If the guard raises an exception during evaluation, the exception bubbles up.

Guards are allowed to have side effects as they are expressions. Guard evaluation must proceed from the first to the last case block, one at a time, skipping case blocks whose pattern(s) don’t all succeed. (I.e., guard evaluation must happen in order.) Guard evaluation must stop once a case block is selected.

8.6.3. Irrefutable Case Blocks ¶

An irrefutable case block is a match-all case block. A match statement may have at most one irrefutable case block, and it must be last.

A case block is considered irrefutable if it has no guard and its pattern is irrefutable. A pattern is considered irrefutable if we can prove from its syntax alone that it will always succeed. Only the following patterns are irrefutable:

AS Patterns whose left-hand side is irrefutable

OR Patterns containing at least one irrefutable pattern

Capture Patterns

Wildcard Patterns

parenthesized irrefutable patterns

8.6.4. Patterns ¶

This section uses grammar notations beyond standard EBNF:

the notation SEP.RULE+ is shorthand for RULE (SEP RULE)*

the notation !RULE is shorthand for a negative lookahead assertion

The top-level syntax for patterns is:

The descriptions below will include a description “in simple terms” of what a pattern does for illustration purposes (credits to Raymond Hettinger for a document that inspired most of the descriptions). Note that these descriptions are purely for illustration purposes and may not reflect the underlying implementation. Furthermore, they do not cover all valid forms.

8.6.4.1. OR Patterns ¶

An OR pattern is two or more patterns separated by vertical bars | . Syntax:

Only the final subpattern may be irrefutable , and each subpattern must bind the same set of names to avoid ambiguity.

An OR pattern matches each of its subpatterns in turn to the subject value, until one succeeds. The OR pattern is then considered successful. Otherwise, if none of the subpatterns succeed, the OR pattern fails.

In simple terms, P1 | P2 | ... will try to match P1 , if it fails it will try to match P2 , succeeding immediately if any succeeds, failing otherwise.

8.6.4.2. AS Patterns ¶

An AS pattern matches an OR pattern on the left of the as keyword against a subject. Syntax:

If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds the subject to the name on the right of the as keyword and succeeds. capture_pattern cannot be a _ .

In simple terms P as NAME will match with P , and on success it will set NAME = <subject> .

8.6.4.3. Literal Patterns ¶

A literal pattern corresponds to most literals in Python. Syntax:

The rule strings and the token NUMBER are defined in the standard Python grammar . Triple-quoted strings are supported. Raw strings and byte strings are supported. f-strings are not supported.

The forms signed_number '+' NUMBER and signed_number '-' NUMBER are for expressing complex numbers ; they require a real number on the left and an imaginary number on the right. E.g. 3 + 4j .

In simple terms, LITERAL will succeed only if <subject> == LITERAL . For the singletons None , True and False , the is operator is used.

8.6.4.4. Capture Patterns ¶

A capture pattern binds the subject value to a name. Syntax:

A single underscore _ is not a capture pattern (this is what !'_' expresses). It is instead treated as a wildcard_pattern .

In a given pattern, a given name can only be bound once. E.g. case x, x: ... is invalid while case [x] | x: ... is allowed.

Capture patterns always succeed. The binding follows scoping rules established by the assignment expression operator in PEP 572 ; the name becomes a local variable in the closest containing function scope unless there’s an applicable global or nonlocal statement.

In simple terms NAME will always succeed and it will set NAME = <subject> .

8.6.4.5. Wildcard Patterns ¶

A wildcard pattern always succeeds (matches anything) and binds no name. Syntax:

_ is a soft keyword within any pattern, but only within patterns. It is an identifier, as usual, even within match subject expressions, guard s, and case blocks.

In simple terms, _ will always succeed.

8.6.4.6. Value Patterns ¶

A value pattern represents a named value in Python. Syntax:

The dotted name in the pattern is looked up using standard Python name resolution rules . The pattern succeeds if the value found compares equal to the subject value (using the == equality operator).

In simple terms NAME1.NAME2 will succeed only if <subject> == NAME1.NAME2

If the same value occurs multiple times in the same match statement, the interpreter may cache the first value found and reuse it rather than repeat the same lookup. This cache is strictly tied to a given execution of a given match statement.

8.6.4.7. Group Patterns ¶

A group pattern allows users to add parentheses around patterns to emphasize the intended grouping. Otherwise, it has no additional syntax. Syntax:

In simple terms (P) has the same effect as P .

8.6.4.8. Sequence Patterns ¶

A sequence pattern contains several subpatterns to be matched against sequence elements. The syntax is similar to the unpacking of a list or tuple.

There is no difference if parentheses or square brackets are used for sequence patterns (i.e. (...) vs [...] ).

A single pattern enclosed in parentheses without a trailing comma (e.g. (3 | 4) ) is a group pattern . While a single pattern enclosed in square brackets (e.g. [3 | 4] ) is still a sequence pattern.

At most one star subpattern may be in a sequence pattern. The star subpattern may occur in any position. If no star subpattern is present, the sequence pattern is a fixed-length sequence pattern; otherwise it is a variable-length sequence pattern.

The following is the logical flow for matching a sequence pattern against a subject value:

If the subject value is not a sequence [ 2 ] , the sequence pattern fails.

If the subject value is an instance of str , bytes or bytearray the sequence pattern fails.

The subsequent steps depend on whether the sequence pattern is fixed or variable-length.

If the sequence pattern is fixed-length:

If the length of the subject sequence is not equal to the number of subpatterns, the sequence pattern fails

Subpatterns in the sequence pattern are matched to their corresponding items in the subject sequence from left to right. Matching stops as soon as a subpattern fails. If all subpatterns succeed in matching their corresponding item, the sequence pattern succeeds.

Otherwise, if the sequence pattern is variable-length:

If the length of the subject sequence is less than the number of non-star subpatterns, the sequence pattern fails.

The leading non-star subpatterns are matched to their corresponding items as for fixed-length sequences.

If the previous step succeeds, the star subpattern matches a list formed of the remaining subject items, excluding the remaining items corresponding to non-star subpatterns following the star subpattern.

Remaining non-star subpatterns are matched to their corresponding subject items, as for a fixed-length sequence.

The length of the subject sequence is obtained via len() (i.e. via the __len__() protocol). This length may be cached by the interpreter in a similar manner as value patterns .

In simple terms [P1, P2, P3, … , P<N>] matches only if all the following happens:

check <subject> is a sequence

len(subject) == <N>

P1 matches <subject>[0] (note that this match can also bind names)

P2 matches <subject>[1] (note that this match can also bind names)

… and so on for the corresponding pattern/element.

8.6.4.9. Mapping Patterns ¶

A mapping pattern contains one or more key-value patterns. The syntax is similar to the construction of a dictionary. Syntax:

At most one double star pattern may be in a mapping pattern. The double star pattern must be the last subpattern in the mapping pattern.

Duplicate keys in mapping patterns are disallowed. Duplicate literal keys will raise a SyntaxError . Two keys that otherwise have the same value will raise a ValueError at runtime.

The following is the logical flow for matching a mapping pattern against a subject value:

If the subject value is not a mapping [ 3 ] ,the mapping pattern fails.

If every key given in the mapping pattern is present in the subject mapping, and the pattern for each key matches the corresponding item of the subject mapping, the mapping pattern succeeds.

If duplicate keys are detected in the mapping pattern, the pattern is considered invalid. A SyntaxError is raised for duplicate literal values; or a ValueError for named keys of the same value.

Key-value pairs are matched using the two-argument form of the mapping subject’s get() method. Matched key-value pairs must already be present in the mapping, and not created on-the-fly via __missing__() or __getitem__() .

In simple terms {KEY1: P1, KEY2: P2, ... } matches only if all the following happens:

check <subject> is a mapping

KEY1 in <subject>

P1 matches <subject>[KEY1]

… and so on for the corresponding KEY/pattern pair.

8.6.4.10. Class Patterns ¶

A class pattern represents a class and its positional and keyword arguments (if any). Syntax:

The same keyword should not be repeated in class patterns.

The following is the logical flow for matching a class pattern against a subject value:

If name_or_attr is not an instance of the builtin type , raise TypeError .

If the subject value is not an instance of name_or_attr (tested via isinstance() ), the class pattern fails.

If no pattern arguments are present, the pattern succeeds. Otherwise, the subsequent steps depend on whether keyword or positional argument patterns are present.

For a number of built-in types (specified below), a single positional subpattern is accepted which will match the entire subject; for these types keyword patterns also work as for other types.

If only keyword patterns are present, they are processed as follows, one by one:

I. The keyword is looked up as an attribute on the subject.

If this raises an exception other than AttributeError , the exception bubbles up. If this raises AttributeError , the class pattern has failed. Else, the subpattern associated with the keyword pattern is matched against the subject’s attribute value. If this fails, the class pattern fails; if this succeeds, the match proceeds to the next keyword.

II. If all keyword patterns succeed, the class pattern succeeds.

If any positional patterns are present, they are converted to keyword patterns using the __match_args__ attribute on the class name_or_attr before matching:

I. The equivalent of getattr(cls, "__match_args__", ()) is called.

If this raises an exception, the exception bubbles up. If the returned value is not a tuple, the conversion fails and TypeError is raised. If there are more positional patterns than len(cls.__match_args__) , TypeError is raised. Otherwise, positional pattern i is converted to a keyword pattern using __match_args__[i] as the keyword. __match_args__[i] must be a string; if not TypeError is raised. If there are duplicate keywords, TypeError is raised. See also Customizing positional arguments in class pattern matching

the match proceeds as if there were only keyword patterns.

For the following built-in types the handling of positional subpatterns is different:

These classes accept a single positional argument, and the pattern there is matched against the whole object rather than an attribute. For example int(0|1) matches the value 0 , but not the value 0.0 .

In simple terms CLS(P1, attr=P2) matches only if the following happens:

isinstance(<subject>, CLS)

convert P1 to a keyword pattern using CLS.__match_args__

For each keyword argument attr=P2 :

hasattr(<subject>, "attr")

P2 matches <subject>.attr

… and so on for the corresponding keyword argument/pattern pair.

8.7. Function definitions ¶

A function definition defines a user-defined function object (see section The standard type hierarchy ):

A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.

The function definition does not execute the function body; this gets executed only when the function is called. [ 4 ]

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code

is roughly equivalent to

except that the original function is not temporarily bound to the name func .

Changed in version 3.9: Functions may be decorated with any valid assignment_expression . Previously, the grammar was much more restrictive; see PEP 614 for details.

A list of type parameters may be given in square brackets between the function’s name and the opening parenthesis for its parameter list. This indicates to static type checkers that the function is generic. At runtime, the type parameters can be retrieved from the function’s __type_params__ attribute. See Generic functions for more.

Changed in version 3.12: Type parameter lists are new in Python 3.12.

When one or more parameters have the form parameter = expression , the function is said to have “default parameter values.” For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter’s default value is substituted. If a parameter has a default value, all following parameters up until the “ * ” must also have a default value — this is a syntactic restriction that is not expressed by the grammar.

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter value is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default parameter value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

Function call semantics are described in more detail in section Calls . A function call always assigns values to all parameters mentioned in the parameter list, either from positional arguments, from keyword arguments, or from default values. If the form “ *identifier ” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “ **identifier ” is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type. Parameters after “ * ” or “ *identifier ” are keyword-only parameters and may only be passed by keyword arguments. Parameters before “ / ” are positional-only parameters and may only be passed by positional arguments.

Changed in version 3.8: The / function parameter syntax may be used to indicate positional-only parameters. See PEP 570 for details.

Parameters may have an annotation of the form “ : expression ” following the parameter name. Any parameter may have an annotation, even those of the form *identifier or **identifier . Functions may have “return” annotation of the form “ -> expression ” after the parameter list. These annotations can be any valid Python expression. The presence of annotations does not change the semantics of a function. The annotation values are available as values of a dictionary keyed by the parameters’ names in the __annotations__ attribute of the function object. If the annotations import from __future__ is used, annotations are preserved as strings at runtime which enables postponed evaluation. Otherwise, they are evaluated when the function definition is executed. In this case annotations may be evaluated in a different order than they appear in the source code.

It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda expressions, described in section Lambdas . Note that the lambda expression is merely a shorthand for a simplified function definition; a function defined in a “ def ” statement can be passed around or assigned to another name just like a function defined by a lambda expression. The “ def ” form is actually more powerful since it allows the execution of multiple statements and annotations.

Programmer’s note: Functions are first-class objects. A “ def ” statement executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section Naming and binding for details.

The original specification for function annotations.

Definition of a standard meaning for annotations: type hints.

Ability to type hint variable declarations, including class variables and instance variables.

Support for forward references within annotations by preserving annotations in a string form at runtime instead of eager evaluation.

Function and method decorators were introduced. Class decorators were introduced in PEP 3129 .

8.8. Class definitions ¶

A class definition defines a class object (see section The standard type hierarchy ):

A class definition is an executable statement. The inheritance list usually gives a list of base classes (see Metaclasses for more advanced uses), so each item in the list should evaluate to a class object which allows subclassing. Classes without an inheritance list inherit, by default, from the base class object ; hence,

is equivalent to

The class’s suite is then executed in a new execution frame (see Naming and binding ), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. [ 5 ] A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace.

The order in which attributes are defined in the class body is preserved in the new class’s __dict__ . Note that this is reliable only right after the class is created and only for classes that were defined using the definition syntax.

Class creation can be customized heavily using metaclasses .

Classes can also be decorated: just like when decorating functions,

The evaluation rules for the decorator expressions are the same as for function decorators. The result is then bound to the class name.

Changed in version 3.9: Classes may be decorated with any valid assignment_expression . Previously, the grammar was much more restrictive; see PEP 614 for details.

A list of type parameters may be given in square brackets immediately after the class’s name. This indicates to static type checkers that the class is generic. At runtime, the type parameters can be retrieved from the class’s __type_params__ attribute. See Generic classes for more.

Programmer’s note: Variables defined in the class definition are class attributes; they are shared by instances. Instance attributes can be set in a method with self.name = value . Both class and instance attributes are accessible through the notation “ self.name ”, and an instance attribute hides a class attribute with the same name when accessed in this way. Class attributes can be used as defaults for instance attributes, but using mutable values there can lead to unexpected results. Descriptors can be used to create instance variables with different implementation details.

The proposal that changed the declaration of metaclasses to the current syntax, and the semantics for how classes with metaclasses are constructed.

The proposal that added class decorators. Function and method decorators were introduced in PEP 318 .

8.9. Coroutines ¶

Added in version 3.5.

8.9.1. Coroutine function definition ¶

Execution of Python coroutines can be suspended and resumed at many points (see coroutine ). await expressions, async for and async with can only be used in the body of a coroutine function.

Functions defined with async def syntax are always coroutine functions, even if they do not contain await or async keywords.

It is a SyntaxError to use a yield from expression inside the body of a coroutine function.

An example of a coroutine function:

Changed in version 3.7: await and async are now keywords; previously they were only treated as such inside the body of a coroutine function.

8.9.2. The async for statement ¶

An asynchronous iterable provides an __aiter__ method that directly returns an asynchronous iterator , which can call asynchronous code in its __anext__ method.

The async for statement allows convenient iteration over asynchronous iterables.

Is semantically equivalent to:

See also __aiter__() and __anext__() for details.

It is a SyntaxError to use an async for statement outside the body of a coroutine function.

8.9.3. The async with statement ¶

An asynchronous context manager is a context manager that is able to suspend execution in its enter and exit methods.

See also __aenter__() and __aexit__() for details.

It is a SyntaxError to use an async with statement outside the body of a coroutine function.

The proposal that made coroutines a proper standalone concept in Python, and added supporting syntax.

8.10. Type parameter lists ¶

Added in version 3.12.

Functions (including coroutines ), classes and type aliases may contain a type parameter list:

Semantically, this indicates that the function, class, or type alias is generic over a type variable. This information is primarily used by static type checkers, and at runtime, generic objects behave much like their non-generic counterparts.

Type parameters are declared in square brackets ( [] ) immediately after the name of the function, class, or type alias. The type parameters are accessible within the scope of the generic object, but not elsewhere. Thus, after a declaration def func[T](): pass , the name T is not available in the module scope. Below, the semantics of generic objects are described with more precision. The scope of type parameters is modeled with a special function (technically, an annotation scope ) that wraps the creation of the generic object.

Generic functions, classes, and type aliases have a __type_params__ attribute listing their type parameters.

Type parameters come in three kinds:

typing.TypeVar , introduced by a plain name (e.g., T ). Semantically, this represents a single type to a type checker.

typing.TypeVarTuple , introduced by a name prefixed with a single asterisk (e.g., *Ts ). Semantically, this stands for a tuple of any number of types.

typing.ParamSpec , introduced by a name prefixed with two asterisks (e.g., **P ). Semantically, this stands for the parameters of a callable.

typing.TypeVar declarations can define bounds and constraints with a colon ( : ) followed by an expression. A single expression after the colon indicates a bound (e.g. T: int ). Semantically, this means that the typing.TypeVar can only represent types that are a subtype of this bound. A parenthesized tuple of expressions after the colon indicates a set of constraints (e.g. T: (str, bytes) ). Each member of the tuple should be a type (again, this is not enforced at runtime). Constrained type variables can only take on one of the types in the list of constraints.

For typing.TypeVar s declared using the type parameter list syntax, the bound and constraints are not evaluated when the generic object is created, but only when the value is explicitly accessed through the attributes __bound__ and __constraints__ . To accomplish this, the bounds or constraints are evaluated in a separate annotation scope .

typing.TypeVarTuple s and typing.ParamSpec s cannot have bounds or constraints.

The following example indicates the full set of allowed type parameter declarations:

8.10.1. Generic functions ¶

Generic functions are declared as follows:

This syntax is equivalent to:

Here annotation-def indicates an annotation scope , which is not actually bound to any name at runtime. (One other liberty is taken in the translation: the syntax does not go through attribute access on the typing module, but creates an instance of typing.TypeVar directly.)

The annotations of generic functions are evaluated within the annotation scope used for declaring the type parameters, but the function’s defaults and decorators are not.

The following example illustrates the scoping rules for these cases, as well as for additional flavors of type parameters:

Except for the lazy evaluation of the TypeVar bound, this is equivalent to:

The capitalized names like DEFAULT_OF_arg are not actually bound at runtime.

8.10.2. Generic classes ¶

Generic classes are declared as follows:

Here again annotation-def (not a real keyword) indicates an annotation scope , and the name TYPE_PARAMS_OF_Bag is not actually bound at runtime.

Generic classes implicitly inherit from typing.Generic . The base classes and keyword arguments of generic classes are evaluated within the type scope for the type parameters, and decorators are evaluated outside that scope. This is illustrated by this example:

This is equivalent to:

8.10.3. Generic type aliases ¶

The type statement can also be used to create a generic type alias:

Except for the lazy evaluation of the value, this is equivalent to:

Here, annotation-def (not a real keyword) indicates an annotation scope . The capitalized names like TYPE_PARAMS_OF_ListOrSet are not actually bound at runtime.

Table of Contents

  • 8.1. The if statement
  • 8.2. The while statement
  • 8.3. The for statement
  • 8.4.1. except clause
  • 8.4.2. except* clause
  • 8.4.3. else clause
  • 8.4.4. finally clause
  • 8.5. The with statement
  • 8.6.1. Overview
  • 8.6.2. Guards
  • 8.6.3. Irrefutable Case Blocks
  • 8.6.4.1. OR Patterns
  • 8.6.4.2. AS Patterns
  • 8.6.4.3. Literal Patterns
  • 8.6.4.4. Capture Patterns
  • 8.6.4.5. Wildcard Patterns
  • 8.6.4.6. Value Patterns
  • 8.6.4.7. Group Patterns
  • 8.6.4.8. Sequence Patterns
  • 8.6.4.9. Mapping Patterns
  • 8.6.4.10. Class Patterns
  • 8.7. Function definitions
  • 8.8. Class definitions
  • 8.9.1. Coroutine function definition
  • 8.9.2. The async for statement
  • 8.9.3. The async with statement
  • 8.10.1. Generic functions
  • 8.10.2. Generic classes
  • 8.10.3. Generic type aliases

Previous topic

7. Simple statements

9. Top-level components

  • Report a Bug
  • Show Source

Semicolon in Python

Semicolon

The common meaning of a semicolon(;) in various programming languages is to end or discontinue the current statement. In programming languages such as C, C++, and Java, it is necessary to use a semicolon to end a line of code. However, this is not the case with Python.

A semicolon in Python signifies separation rather than termination. It allows you to write multiple statements on a single line.

There are many use cases of semicolons than just mentioned above, in this tutorial we will see different uses of semicolons in Python and understand it better with examples.

Why are semicolons allowed in Python?

Python does not require semi-colons to terminate statements. Semicolons can be used to delimit statements if you wish to put multiple statements on the same line.

A  semicolon  in  Python  denotes separation, rather than termination. It allows you to write multiple statements on the same line. This syntax also makes it  legal  to put a  semicolon  at the end of a single statement. So, it’s actually two statements and the second one is empty.

How to print a semicolon in Python?

Many people consider the semicolon to be different from other alphabets. Let’s see what happens when we try to print a semicolon as a regular string in Python

It treats the semicolon no differently and prints it out.

Split Statements with Semicolons

Sometimes there is a need to write multiple statements in a line to make the code single liners or for some other reason, in this type of case semicolons are very useful. A semicolon can be used to separate statements in Python.

Below is the syntax for using a semicolon to separate two statements, but these statements can be more than two.

In this example, we will try to put more than 2 statements in a single line with the use of the semicolon.

Here are the three statements in Python without semicolons:

Now let’s use the same three statements with semicolons

As you can see, Python executes the three statements individually after we split them with semicolons. Without the use of that, the interpreter would give us an error.

Using Semicolons with Loops in Python

In loops like the For loop , a semicolon can be used if the whole statement starts with a loop. You use a semicolon to form a coherent statement like the body of the loop.

In this example, we’ll try to loop through two statements separated by a semicolon and see if the loop prints both or just the first one.

Here we have used the range() method to specify a loop to execute statements four times.

In the above output, we can see that it successfully prints both statements the specified number of times, which means it can loop through all the statements separated by semicolons.

Python will throw an error if you use a semicolon to separate a normal expression from a block statement i.e loop.

In this tutorial, we have learned various use cases of a semicolon in Python. Let’s summarize them with two pointers:

  • A semicolon in Python is mostly used to separate multiple statements written on a single line.
  • A semicolon is used to write a minor statement and reserve a bit of space like name = Marie; age = 23; print(name, age)

The use of semicolons is very “non-pythonic” and it is recommended not to be used unless you desperately need it.

https://stackoverflow.com/questions/8236380/why-is-semicolon-allowed-in-this-python-snippet

IMAGES

  1. How to Colon of a tuple in Python

    python colon before assignment

  2. PYTHON : what is the meaning of colon in python's string format?

    python colon before assignment

  3. When To Use Colon (:) in Python?

    python colon before assignment

  4. The Real Use Of "::" (Double Colon) in Python Explained

    python colon before assignment

  5. How to Use Double Colon Operator (::) in Python List (3 Examples)

    python colon before assignment

  6. Colon in Python

    python colon before assignment

VIDEO

  1. Thought you knew slicing? Slicing is more confusing than you think

  2. Slicing Strings

  3. "Mastering Assignment Operators in Python: A Comprehensive Guide"

  4. 76-Python-exception handling-6-customs exceptions-codes| Data Science With Python| HINDI

  5. Python dictionary in Tamil

  6. Python dictionary in Tamil

COMMENTS

  1. python

    Use of colon in variable declaration [duplicate] Ask Question Asked 5 years, 9 months ago. Modified 2 years, 5 months ago. Viewed 56k times ... Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in the __annotations__ attribute of a class or module.

  2. Colon in Python

    Double Colons (::) in Python. The double colons (::) in python are used for jumping of elements in multiple axes. It is also a slice operator. Every item of the sequence gets sliced using double colon. Take for example a string 'Ask python' and we'll try to manipulate it using the slice operator for better understanding.

  3. PEP 526

    Annotations for module level variables, class and instance variables, and local variables should have a single space after corresponding colon. There should be no space before the colon. If an assignment has right hand side, then the equality sign should have exactly one space on both sides. Examples: Yes:

  4. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

  5. The Ultimate Guide to Python's Colon Operator

    The colon operator, represented by the ':' symbol, is a fundamental feature of the Python language. It is primarily used to indicate the start of a code block or to separate the start and end indices in slicing operations. Let's delve deeper into its definition, syntax, and its role in Python programming. In Python, the colon operator is ...

  6. When To Use Colon (:) in Python?

    Te colon lies between the parameter name and its data type. 8. For declaring classes. Python is an OOP language. So, to declare classes we need to use the colons. The colon decides the scope of a variable and the function of a class. This is to signal the interpreter that entities of a class lie under a colon. Here is one simple example: Code:

  7. PEP 572

    Unparenthesized assignment expressions are prohibited for the value of a keyword argument in a call. Example: foo(x = y := f(x)) # INVALID foo(x=(y := f(x))) # Valid, though probably confusing. This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

  8. Assignment Expressions: The Walrus Operator

    In this lesson, you'll learn about the biggest change in Python 3.8: the introduction of assignment expressions.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.

  9. Why and when you need to use colon (:) in Python

    The code above shows when you need to use a colon to start an indented block. 2. To slice a list or a string. Colons are also used to slice a list or a string in Python. The slicing syntax is as follows: string[start:end:step] The three numbers marking the start, end, and step in a slice is separated using colons.

  10. PEP 8

    Python Enhancement Proposals. Python » PEP Index » PEP 8; Toggle light / dark / auto colour theme PEP 8 - Style Guide for Python Code ... There should be no space before the colon. If an assignment has a right hand side, then the equality sign should have exactly one space on both sides: # Correct: code: ...

  11. What Does Colon Equals Mean In Python? The New Walrus Operator

    Summary. The walrus operator is a new assignment operator introduced in Python 3.8 that can enable leaner code by assigning the value of a variable that can be used elsewhere in your code. This can save having to declare the result of the assignment elsewhere in your code as demonstrated above with the regular expression code.

  12. 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.

  13. Python local variable referenced before assignment Solution

    Trying to assign a value to a variable that does not have local scope can result in this error: UnboundLocalError: local variable referenced before assignment. Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function, that variable is local. This is because it is assumed that when you define a ...

  14. 8. Compound statements

    Compound statements — Python 3.12.3 documentation. 8. Compound statements ¶. Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in ...

  15. Is colon in python blocks technically necesary?

    5. The Cobra Programming Language 's syntax is heavily inspired by Python's, and it does away with the colon, so it seems that it is not strictly necessary. However, it is not enough to just remove the colon, there are other changes to the syntax needed. See, for example this piece of code from one of my toy projects:

  16. What does colon at assignment for list[:] = [...] do in Python

    73. This syntax is a slice assignment. A slice of [:] means the entire list. The difference between nums[:] = and nums = is that the latter doesn't replace elements in the original list. This is observable when there are two references to the list. # original and other refer to. To see the difference just remove the [:] from the assignment above.

  17. Conditional Statements in Python

    In the form shown above: <expr> is an expression evaluated in a Boolean context, as discussed in the section on Logical Operators in the Operators and Expressions in Python tutorial. <statement> is a valid Python statement, which must be indented. (You will see why very soon.) If <expr> is true (evaluates to a value that is "truthy"), then <statement> is executed.

  18. Semicolon in Python

    A semicolon can be used to separate statements in Python. Below is the syntax for using a semicolon to separate two statements, but these statements can be more than two. Syntax: statement1; statement2. Example: In this example, we will try to put more than 2 statements in a single line with the use of the semicolon.

  19. Colon (:) in Python list index

    I'm new to Python. I see : used in list indices especially when it's associated with function calls.. Python 2.7 documentation suggests that lists.append translates to a[len(a):] = [x].Why does one need to suffix len(a) with a colon?. I understand that : is used to identify keys in dictionary.