Skip to content

Context and TypedDict #280

Closed
Closed

Description

@MosGeo

I am just getting into app-model and its features. I noticed that context is typed as MutableMapping which makes sense. In my case, I want to use typing. I ended up using TypedDict as it is typed. It seems to work (if you ignore the warning).

  1. Is there a side effect issue of using TypedDict? If not, i suggest the inclusion of TypedDict as a possible type for the context variable.
  2. Is there anythong way to use a class? some of the AIs are suggesting to use ContextNamespace but i am not sure how to use and couldn't get it to work.

Activity

  1. tlambert03 commented on May 8, 2026

    @tlambert03
    Member

    hey @MosGeo

    there are some subtleties here, and lots of room for improvement, Ultimately though, I would just suggest using type ignore or casting dict(my_dict) when you pass it into the Application, and move on with your life:

    • conceptually, you really can think of a context as any old mutable mapping. That "mutable" part is important however... And a TypedDict is not, technically speaking, a MutableMapping (since it has a fixed set of keys... yes, you can mutate the value of any of those keys, but because it doesn't accept new keys, it's not actually a MutableMapping).
    • When you pass a mapping into the Application constructor, it uses it to create a Context object (Context(your_object)). That doesn't copy the dictionary, it stores it directly. Arguably, we could just call dict(your_object), and then we could relax the type hint to context: Mapping (but, we still couldn't use TypedDict as a possible type ... it's not correct here). But you can also just pass context=dict(your_object) yourself and that would also work.

    I definitely concede that the ContextNamespace thing isn't very intuitive. I'm working on docs in #284 ... but even as I write them I'm not super happy with the mental mode. However, to get you started, here's a rough example of how you would currently use ContextNamespace to get static typing of context values, and (the more important bit) use the keys directly in expressions (claude made this example, but I read it and agree):

    from __future__ import annotations
    
    from app_model import Action, Application
    from app_model.expressions import ContextKey, ContextNamespace
    
    
    # 1. Declare your typed namespace -----------------------------------------
    # `ContextNamespace[A]` is generic in the type passed to a (rarely-used)
    # `getter` callback; if you don't use getters, `object` is fine.
    # `ContextKey[A, T]` annotations are what give static typing on reads/writes.
    class AppKeys(ContextNamespace[object]):
        selected_count: ContextKey[object, int] = ContextKey(
            default_value=0,
            description="Number of currently selected items.",
        )
        is_dirty: ContextKey[object, bool] = ContextKey(
            default_value=False,
            description="Whether the document has unsaved changes.",
        )
        document_title: ContextKey[object, str] = ContextKey(
            default_value="Untitled",
            description="Title of the active document.",
        )
    
    
    # 2. Bind the namespace to the app's context ------------------------------
    app = Application.get_or_create("my-app")
    keys = AppKeys(app.context)  # <-- the binding step that's easy to miss
    
    
    # 3. Typed reads and writes -----------------------------------------------
    assert keys.selected_count == 0  # int (typed)
    keys.selected_count = 3  # OK
    keys.is_dirty = True  # OK
    # keys.selected_count = "three"    # mypy/pyright would flag this
    
    # The namespace and the underlying context share storage:
    assert app.context["selected_count"] == 3
    
    
    # 4. The payoff: build expressions from the *class* attributes ------------
    # AppKeys.selected_count is a ContextKey, which IS an Expr -- usable
    # directly in `enablement` / `when` clauses, no string parsing needed.
    has_selection = AppKeys.selected_count > 0
    needs_save = AppKeys.is_dirty & (AppKeys.document_title != "Untitled")
    
    assert has_selection.eval({"selected_count": 3}) is True
    assert has_selection.eval(app.context) is True  # works on a live Context too
    
    
    def delete_selection() -> None:
        print(f"deleting {keys.selected_count} items")
    
    
    app.register_action(
        Action(
            id="my-app.delete",
            title="Delete Selection",
            callback=delete_selection,
            enablement=has_selection,  # ← typed ContextKey, not a string
        )
    )

    if you don't want to use that

    1. you can just stick with your TypedDict. and, if you want to retain static typing whenever you access the app.context property, you should just typed_ctx = cast(YourDict, app.context). (this is also not mutually exclusive with the ContextNamespace approach above).
    2. you could also just pass a TypedDict as the context (with type ignore) and keep the reference
      seed: MyCtx = {"selected_count": 0, "is_dark": True}                                                                                            
      app = Application("my-app", context=seed)   # type: ignore

    This works because Application adopts the dict directly (as we discussed earlier)


    anyway, there's a number of options from simple to complex.

  2. tlambert03 commented on Nov 20, 2026

    @tlambert03
    Member

    #284 (now merged) adds docs on contexts, expressions and ContextNamespace, including the typed ContextKey[A, T] pattern from the example above. so I'm going to close this one... if there's something those docs don't cover, let me know!

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions