Skip to content

with statement star target #135617

Description

@wwotex

Documentation

https://docs.python.org/3/reference/simple_stmts.html#grammar-token-python-grammar-target

According to the docs, the grammar for the with statement allows:

with_stmt                          ::= "with" with_stmt_contents
with_stmt_contents           ::= with_item
with_item                          ::= expression "as" target
target                                ::= identifier  | "*" target

from my understanding that would allow a python syntax like this:

class Test:
    def __enter__(self):
        return (1, 2)

    def __exit__(self, exc_type, exc_value, traceback):
        pass


with Test() as *mambo:
    print(mambo, type(mambo))

But for me with python version 3.12.8

I get a syntax error:

  File "/home/gringo/accessia/main/controller_start/test.py", line 9
    with Test() as *mambo:
                   ^^^^^^
SyntaxError: starred assignment target must be in a list or tuple

Linked PRs

Activity

  1. HLLRay commented on Jun 17, 2025

    @HLLRay
  2. zware commented on Jun 17, 2025

    @zware
    Member
    with Test() as (*mambo,):
        print(mambo, type(mambo))

    does give [1, 2] <class 'list'>, as does with Test() as [*mambo]:. I'm not a grammar expert, but I believe there are some places where the tuple is implicit so that "*" target is valid and other places where the ()/[] are required to be explicitly added. I'm not sure whether/how the documentation can be improved here.

  3. iritkatriel commented on Jun 20, 2025

    @iritkatriel
    Member

    We can do this:

    >>> with Test() as mambo:
    ...     print(mambo, type(mambo))
    ...     
    (1, 2) <class 'tuple'>
    

    What would be the purpose/expected behaviour of with Test() as *mambo:?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions