pg.ContextualObject

Accessible via pg.ContextualObject, pg.symbolic.ContextualObject.

class ContextualObject[source]

Bases: pg.Object

Base class for contextual objects.

Contextual objects are objects whose attributes can be dynamically overridden using pg.contextual_override or resolved through pg.contextual_attribute, allowing them to inherit values from their containing objects.

Usages:

``` # Define a contextual object. class A(pg.ContextualObject):

x: int y: Any = pg.contextual_attribute()

# Create an instance of A a = A(1) print(a.x) # Outputs: 1 print(a.y) # Raises an error, as a has no containing object.

# Define another contextual object containing an instance of A class B(pg.ContextualObject):

y: int a: A

# Create an instance of B, containing “a” b = B(y=2, a=a) print(a.y) # Outputs: 2, as “y” is resolved from the containing object (B).

# Contextual overrides are thread-specific with pg.contextual_override(x=2):

print(a.x) # Outputs: 2

# Thread-specific behavior of pg.contextual_override def foo(a):

print(a.x)

with pg.contextual_override(x=3):

t = threading.Thread(target=foo, args=(a,)) t.start() t.join() # Outputs: 1, because pg.contextual_override is limited to the current # thread to avoid clashes in multi-threaded environments.

# To propagate the override to a new thread, use pg.with_contextual_override with pg.contextual_override(x=3):

t = threading.Thread(target=pg.with_contextual_override(foo), args=(a,)) t.start() t.join() # Outputs: 3, as the override is explicitly propagated.

```

Methods:

override(**kwargs)

Context manager to override the attributes of this component.

override(**kwargs)[source]

Context manager to override the attributes of this component.

Return type:

ContextManager[Dict[str, pg.utils.ContextualOverride]]