Skip to content

state

Functions:

  • copy_state

    Copy PyBooster's current state and return a callback that will set it in another context.

copy_state

copy_state() -> StateSetter

Copy PyBooster's current state and return a callback that will set it in another context.

Example

If you need to run a function in a different context, you can use this function to copy the state established there and set it in the new context. This might happen if you create a thread (which has its own context) to run a function that creates some PyBooster state which you'd then like to use in the main thread.

from concurrent.futures import Future
from threading import Thread
from typing import NewType

from pybooster import injector, new_scope, get_scope
from pybooster.core.state import copy_state

Greeting = NewType("Greeting", str)


def from_thread(future):
    with new_scope({Greeting: "Hello"}):
        set_state = copy_state()
        future.set_result(set_state)


set_state_future = Future()
thread = Thread(target=from_thread, args=(set_state_future,))
thread.start()
set_state = set_state_future.result()

reset_state = set_state()
assert get_scope().get(Greeting) == "Hello"

reset_state()
assert get_scope().get(Greeting) is None