Skip to content

Add expression form of with #76

Closed
Closed

Description

@Technologicat

We already have raisef and tryf, functional loops, the do[] macro to write imperative code in an expression position... the last missing major piece of the puzzle is to support invoking context managers in an expression position.

So, in a future release, let's add a withf, in the spirit of the already existing tryf.

And then update the rant in doc/design-notes.md.

Activity

  1. added
    enhancement
    on Jun 6, 2021
  2. added this to the 0.15.x milestone on Jun 6, 2021
  3. modified the milestones: 0.15.x, 0.15.1 on Jun 22, 2021
  4. modified the milestones: 0.15.1, 0.15.2 on Dec 8, 2021
  5. modified the milestones: 0.15.3, ∞, 0.15.x on Sep 26, 2024
  6. modified the milestones: 1.x, 2.2.0 on Apr 24, 2026
  7. Technologicat commented on May 5, 2026

    @Technologicat
    OwnerAuthor

    Done in b6423e7 (master, will land in 2.2.0).

    Summary of the design as shipped:

    • Single CM or sequence. Pass either a bare context manager or a tuple (cm1, cm2, ...). Multiple CMs are entered left-to-right and exited in reverse, analogously to with cm1, cm2, ...:. Implementation uses contextlib.ExitStack for correct exit ordering and exception propagation.
    • Body arity auto-detected. If body accepts as many positional arguments as there are CMs, it receives the as-values, in order; if it is a 0-arg thunk, the as-values are discarded (the with lock: ... style). Same convention as tryf's exception handler.
    • Return value passes through. Whatever body returns is what withf returns. with is treated as an expression here even though Python's statement form is value-less — value of everything, cost of nothing.

    The rant in doc/design-notes.md is updated; the lambda-limitations bullet now points at withf instead of "we'll add this someday".

    — Claude (Opus 4.7)

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

    enhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions