foundry.core package#
Subpackages#
- foundry.core.graphics_page package
- foundry.core.graphics_set package
- foundry.core.painter package
- foundry.core.player_animations package
- foundry.core.warnings package
- Submodules
- foundry.core.warnings.EnemyCompatibilityWarning module
- foundry.core.warnings.ExtendToGroundWarning module
- foundry.core.warnings.InvalidObjectWarning module
- foundry.core.warnings.InvalidPositionWarning module
- foundry.core.warnings.InvalidSizeWarning module
- foundry.core.warnings.InvalidWarpWarning module
- foundry.core.warnings.OutsideLevelBoundsWarning module
- foundry.core.warnings.Warning module
- foundry.core.warnings.WarningCreator module
- foundry.core.warnings.WarningType module
- foundry.core.warnings.util module
- Module contents
Submodules#
foundry.core.Data module#
foundry.core.UndoController module#
- class UndoController(initial_state: T, undo_stack: collections.deque[foundry.core.UndoController.T] | None = None, redo_stack: collections.deque[foundry.core.UndoController.T] | None = None)#
Bases:
Generic
[T
]A controller for handling both undo and redo
- Parameters:
- GenericT
The state being stored by the UndoController.
- property can_redo: bool#
Determines if there is any states inside the redo stack.
- Returns:
- bool
If there is an redo state available.
- property can_undo: bool#
Determines if there is any states inside the undo stack.
- Returns:
- bool
If there is an undo state available.
- do(new_state: T) T #
Does an action through the controller, adding it to the undo stack and clearing the redo stack, respectively.
- Parameters:
- new_stateT
The new state to be stored.
- Returns:
- T
The new state that has been stored.
- redo() T #
Redoes the previously undone state.
- Returns:
- T
The new state that has been stored.
- property state: T#
- undo() T #
Undoes the last state, bring the previous.
- Returns:
- T
The new state that has been stored.
foundry.core.file module#
- class FilePath(*args, **kwargs)#
Bases:
Path
,ConcreteValidator
,SingleArgumentValidator
foundry.core.geometry module#
- class Point(x: int, y: int)#
Bases:
ConcreteValidator
,KeywordValidator
,Vector2D
,Bound
A two dimensional representation of a point on a plain.
- Attributes:
- x: int
The horizontal location of the point.
- y: int
The vertical location of the point.
- property distance_from_origin: float#
The distance this point is from the origin, Point(0, 0).
- Returns:
- float
The distance from the origin.
- evolve(*, x: int | None = None, y: int | None = None) Self #
A convenience method to modify points quicker.
- Parameters:
- xint | None, optional
The x point that can be evolved, by default will not evolve.
- yint | None, optional
The y point that can be evolved, by default will not evolve.
- Returns:
- Self
The new evolved point.
- classmethod from_components(i_component: int, j_component: int) Self #
Generates a point from the points of a vector.
- Parameters:
- i_componentint
The x position of the point.
- j_componentint
The y position of the point.
- Returns:
- Self
The point created from the two components.
- classmethod from_qt(point: PySide6.QtCore.QPoint | PySide6.QtCore.QPointF) Self #
Generates a point from a QPoint for easy conversion.
- Parameters:
- pointQPoint | QPointF
To be converted.
- Returns:
- Self
Of the QPoint represented inside Python.
- classmethod from_vector(vector: Vector2D) Self #
Generates a point from a vector.
- Parameters:
- vectorVector2D
The vector with the i and j components representing the x and y positions of the point, respectively.
- Returns:
- Self
The point created from the vector.
- to_qt() QPoint #
Converts a point to its PySide equivalent.
- Returns:
- QPoint
The point in Qt’s framework.
- classmethod validate(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
- class Rect(point: Point, size: Size)#
Bases:
ConcreteValidator
,KeywordValidator
,SimpleBound
A two dimensional representation of a box, that uses
attrs
to create a basic implementation.- Attributes:
- point: Point
The upper left corner of the rect.
- size: Size
The size of the box.
- evolve(*, top: int | None = None, bottom: int | None = None, left: int | None = None, right: int | None = None) Self #
- to_qt() QRect #
Generates a QRect from a Rect.
- Parameters:
- rectRect
The rect to be converted to a Rect.
- Returns:
- QRect
The QRect derived from the Rect.
- classmethod validate(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
- class Size(width: int, height: int)#
Bases:
ConcreteValidator
,KeywordValidator
,Vector2D
A two dimensional representation of a size.
- Attributes:
- width: int
The width of the object being represented.
- height: int
The height of the object being represented.
- classmethod from_components(i_component: int, j_component: int) Self #
Generates a size from the components of a vector.
- Parameters:
- i_componentint
The width of the size.
- j_componentint
The height of the size.
- Returns:
- Self
The size created from the two components.
- classmethod from_qt(size: QSize) Self #
Generates a size from a QSize for easy conversion.
- Parameters:
- sizeQSize
To be converted.
- Returns:
- Self
Of the QSize represented inside Python.
- classmethod from_vector(vector: Vector2D) Self #
Generates a size from a vector.
- Parameters:
- vectorVector2D
The vector with the i and j components representing the width and height positions of the point, respectively.
- Returns:
- Self
The size created from the vector.
- to_qt() QSize #
Generates a QSize from a Size.
- Parameters:
- rectSize
The rect to be converted to a Size.
- Returns:
- QSize
The QSize derived from the Size.
- classmethod validate(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
foundry.core.gui module#
- class Action(actor: UndoRedoActor | None, action: Callable[[], _T], reverse_action: Callable[[], _T], name: str = '')#
Bases:
Generic
[_T
]A representation of an action.
- Parameters:
- Generic_T
The type of actions that are applied.
- Attributes:
- actor: UndoRedoActor | None
The object that is responsible for this action.
- action: Callable[[], _T]
The action taken.
- reverse_action: Callable[[], _T]
The action required to undo action.
- name: str
A name, purely for easier debugging.
- peak_: _T | None
A suggestion of what the actual will look like.
- actor: foundry.core.gui.UndoRedoActor | None#
- class Border(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
Bases:
Enum
- DASHED = 3#
- DOUBLE = 5#
- GROOVE = 6#
- INSET = 8#
- NONE = 1#
- OUTSET = 9#
- RIDGE = 7#
- ROUND_DASHED = 2#
- SOLID = 4#
- class Click(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
Bases:
Enum
- BACK_CLICK = 4#
- EXTRA_CLICK_0 = 6#
- EXTRA_CLICK_1 = 7#
- EXTRA_CLICK_2 = 8#
- EXTRA_CLICK_3 = 9#
- EXTRA_CLICK_4 = 10#
- EXTRA_CLICK_5 = 11#
- EXTRA_CLICK_6 = 12#
- EXTRA_CLICK_7 = 13#
- EXTRA_CLICK_8 = 14#
- EXTRA_CLICK_9 = 15#
- FORWARD_CLICK = 5#
- LEFT_CLICK = 1#
- MIDDLE_CLICK = 3#
- OTHER = 16#
- RIGHT_CLICK = 2#
- classmethod from_qt(button: MouseButton)#
- exception ConnectionError#
Bases:
ValueError
An exception that is raised when a subscriber was failed to be connected to a signal.
- class DialogControl(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
Bases:
Enum
- ACCEPT = 1#
- HELP = 3#
- REJECT = 2#
- class DialogEvent(control: DialogControl, suggestion: Optional[_T])#
Bases:
Generic
[_T
]- control: DialogControl#
- class Edge(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
-
- BottomEdge = 8#
- LeftEdge = 2#
- NoEdge = 0#
- RightEdge = 4#
- TopEdge = 1#
- classmethod from_qt(edge: Edge)#
- class EmittingProperty(attributes: collections.abc.Sequence[str] | collections.abc.Sequence[foundry.core.gui._SignalAttribute], fget: collections.abc.Callable[[foundry.core.gui.Object], foundry.core.gui._T] | None = None, fset: collections.abc.Callable[[foundry.core.gui.Object, foundry.core.gui._T], None] | None = None, name: str | None = None, doc: str | None = None)#
Bases:
Generic
[_T
]- fget: collections.abc.Callable[[foundry.core.gui.Object], foundry.core.gui._T] | None#
- fset: collections.abc.Callable[[foundry.core.gui.Object, foundry.core.gui._T], None] | None#
- getter(fget: collections.abc.Callable[[Any], foundry.core.gui._T] | None)#
- setter(fset: collections.abc.Callable[[Any, foundry.core.gui._T], None] | None)#
- class Focus(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
-
- ACTIVE_WINDOW = 3#
- CLICK = 2#
- MENU_BAR = 6#
- NONE = 0#
- OTHER = 7#
- POPUP = 4#
- SHORTCUT = 5#
- STRONG = 11#
- TAB = 1#
- WHEEL = 15#
- class FocusEvent(has_focus: bool, reason: Focus)#
Bases:
object
- classmethod from_qt(event: QFocusEvent)#
- class Key(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
-
- A = 65#
- ALT = 16777251#
- AMPERSAND = 38#
- APOSTROPHE = 39#
- ASTERISK = 42#
- AT = 64#
- B = 66#
- BACK_SLASH = 92#
- BACK_SPACE = 16777219#
- BACK_TAB = 16777218#
- BAR = 124#
- C = 67#
- CAPS_LOCK = 16777252#
- CARROT = 94#
- CLEAR = 16777227#
- COLON = 58#
- COMMA = 44#
- CONTROL = 16777249#
- D = 68#
- DELETE = 16777223#
- DOLLAR = 36#
- DOUBLE_QUITE = 34#
- DOWN = 16777237#
- E = 69#
- END = 16777233#
- ENTER = 16777221#
- EQUAL = 61#
- ESCAPE = 16777216#
- EXCLAMATION_MARK = 33#
- F = 70#
- F1 = 16777264#
- F10 = 16777273#
- F11 = 16777274#
- F12 = 16777275#
- F13 = 16777276#
- F14 = 16777277#
- F15 = 16777278#
- F16 = 16777279#
- F17 = 16777280#
- F18 = 16777281#
- F19 = 16777282#
- F2 = 16777265#
- F20 = 16777283#
- F21 = 16777284#
- F22 = 16777285#
- F23 = 16777286#
- F24 = 16777287#
- F25 = 16777288#
- F26 = 16777289#
- F27 = 16777290#
- F28 = 16777291#
- F29 = 16777292#
- F3 = 16777266#
- F30 = 16777293#
- F31 = 16777294#
- F32 = 16777295#
- F33 = 16777296#
- F34 = 16777297#
- F35 = 16777298#
- F4 = 16777267#
- F5 = 16777268#
- F6 = 16777269#
- F7 = 16777270#
- F8 = 16777271#
- F9 = 16777272#
- G = 71#
- GREATER_THAN = 62#
- H = 72#
- HASHTAG = 35#
- HOME = 16777232#
- I = 73#
- INSERT = 16777222#
- J = 74#
- K = 75#
- L = 76#
- LEFT = 16777234#
- LEFT_BRACE = 123#
- LEFT_BRACKET = 91#
- LEFT_PARENTHESES = 40#
- LEFT_QUOTE = 96#
- LESS_THAN = 60#
- M = 77#
- META = 16777250#
- MINUS = 45#
- N = 78#
- NUMBER_0 = 48#
- NUMBER_1 = 49#
- NUMBER_2 = 50#
- NUMBER_3 = 51#
- NUMBER_4 = 52#
- NUMBER_5 = 53#
- NUMBER_6 = 54#
- NUMBER_7 = 55#
- NUMBER_8 = 56#
- NUMBER_9 = 57#
- NUMS_LOCK = 16777253#
- O = 79#
- P = 80#
- PAGE_DOWN = 16777239#
- PAGE_UP = 16777238#
- PAUSE = 16777224#
- PERCENT = 37#
- PERIOD = 46#
- PLUS = 43#
- PRINT = 16777225#
- Q = 81#
- QUESTION_MARK0 = 63#
- R = 82#
- RETURN = 16777220#
- RIGHT = 16777236#
- RIGHT_BRACE = 125#
- RIGHT_BRACKET = 93#
- RIGHT_PARENTHESES = 41#
- S = 83#
- SCROLL_LOCK = 16777254#
- SEMICOLON = 59#
- SHIFT = 16777248#
- SLASH = 47#
- SPACE = 32#
- SYSTEM_REQUEST = 16777226#
- T = 84#
- TAB = 1048577#
- TILDE = 126#
- U = 85#
- UNDERSCORE = 95#
- UP = 16777235#
- V = 86#
- W = 87#
- X = 88#
- Y = 89#
- Z = 90#
- class KeyEvent(key: foundry.core.gui.Key | None, modifiers: set[foundry.core.gui.Modifier])#
Bases:
object
- classmethod from_qt(event: QKeyEvent)#
- key: foundry.core.gui.Key | None#
- modifiers: set[foundry.core.gui.Modifier]#
- class KeySequence(key: Key, primary_modifier: foundry.core.gui.Modifier | None = None, secondary_modifier: foundry.core.gui.Modifier | None = None, tertiary_modifier: foundry.core.gui.Modifier | None = None)#
Bases:
object
- primary_modifier: foundry.core.gui.Modifier | None#
- secondary_modifier: foundry.core.gui.Modifier | None#
- tertiary_modifier: foundry.core.gui.Modifier | None#
- class Modifier(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
Bases:
Enum
- ALT = 3#
- CONTROL = 2#
- OTHER = 4#
- SHIFT = 1#
- classmethod from_qt(modifier: Qt.KeyboardModifier.KeyboardModifiers)#
- class MouseEvent(global_point: Point, local_point: Point, click: foundry.core.gui.Click | None, modifiers: set[foundry.core.gui.Modifier])#
Bases:
object
- click: foundry.core.gui.Click | None#
- classmethod from_qt(event: QMouseEvent)#
- modifiers: set[foundry.core.gui.Modifier]#
- class MouseWheelEvent(global_point: Point, local_point: Point, click: foundry.core.gui.Click | None, modifiers: set[foundry.core.gui.Modifier], angle_delta: foundry.core.geometry.Point | None)#
Bases:
MouseEvent
- angle_delta: foundry.core.geometry.Point | None#
- classmethod from_qt(event: QWheelEvent)#
- property orientation: Orientation#
- class Object(model: BaseModel, parent: foundry.core.gui.Object | None = None, *args, **kwargs)#
Bases:
_Object
The heart of any GUI component. This component bridges the gap between action and state; it provides the interface for interpreting events derived from signals and converts them into a function onto its model.
- Attributes:
- __signals__: Sequence[Signal]
The list of all signals associated for a given type of object.
- __listeners__: Mapping[str, Sequence[str]]
The list of all internal subscribers for a given type of object.
- updated: SignalInstance[BaseModel]
A signal announces a change in state of an instance of an object.
- final connect_child(attribute: str, child: Object, child_signal_name: str = 'updated', child_attribute: str = 'model', link_child: bool = True) None #
- property model: BaseModel#
The representation of the current state of this instance.
- Returns:
- BaseModel
The current state of this instance.
- property signal_blocker: SignalBlocker#
Provides a context manager to block all signals of this instance.
- Returns:
- SignalBlocker
A context manager which can block every signal of this instance.
- property signals: Sequence[SignalInstance]#
Provides every signal associated with an object.
- Returns:
- Sequence[SignalInstance]
Every signal associated with an instance.
- updated: SignalInstance[BaseModel] = Signal(subscribers=[], name='updated', _dead_subscribers=False)#
- class ObjectMeta(name, bases, attrs)#
Bases:
ObjectType
- class Orientation(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
-
- HORIZONTAL = 1#
- VERTICAL = 2#
- class Selection(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
Bases:
Enum
- NONE = 1#
- PRIMARY = 2#
- REDO = 6#
- SECONDARY = 3#
- TERTIARY = 4#
- UNDO = 5#
- class Signal(*, subscribers: None = None, name: str | None = None)#
- class Signal(*args: Sequence[_SignalElement], subscribers: Sequence[_SignalElement], name: str | None = None)
- class Signal(*args: _SignalElement, subscribers: None = None, name: str | None = None)
Bases:
Generic
[_T
]A representation of an observable action which can be communicated.
- Parameters:
- Generic_T
The result of the action took.
- Attributes:
- subscribers: list[_SignalElement]
A list of interested parties which will be called when the action of interest is taken.
- name: str | None
The user friendly name of this signal, None by default.
- _dead_subscribers: bool
If there exists a subscriber which needs to be collected by the garbage collector.
- clear(**kwargs: ~typing.~_P)#
- connect(**kwargs: ~typing.~_P)#
- disconnect(**kwargs: ~typing.~_P)#
- emit(**kwargs: ~typing.~_P)#
- is_silenced(**kwargs: ~typing.~_P)#
- silence(**kwargs: ~typing.~_P)#
- class SignalBlocker(signal: foundry.core.gui.SignalInstance | collections.abc.Sequence[foundry.core.gui.SignalInstance])#
Bases:
object
A context manager for blocking specific signals.
Notes
This context manager ensures that signals will remain silenced if they were set prior.
- Attributes:
- signal: SignalInstance | Sequence[SignalInstance]
The signals to be blocked temporarily.
- _silenced: bool | Sequence[bool]
The prior state of the signals.
- class SignalInstance(instance: object, signal: Signal[_T])#
Bases:
Generic
[_T
]A representation of a signal with respect to a specific provided instance.
- Parameters:
- Generic_T
The value provided by the signal.
Notes
The primary purpose of this class is to encapsulate the signal with respect to the instance. By doing this, it makes it much hard to mistakenly override other instance’s signal-subscriber relationships. It also provides a series of helper methods to ease use with the signal architecture.
- Attributes:
- instance: object
The instance of interest with respect to signal.
- signal: Signal[_T]
The underlying signal.
- connect(subscriber: Callable[[_T], None], weak: bool = True, max_uses: int | None = None) None #
Associates a subscriber to this signal, to be called when this signal instance receives an action.
- Parameters:
- subscriberCallable[[_T], None]
The subscriber, which takes the result of the action from this signal instance.
- weakbool, optional
If the subscriber should automatically be removed when it is no longer required, by default True
- max_usesint | None, optional
Determines if the subscriber should be removed after a fixed number of uses, by default None or infinite uses are permitted.
- disconnect(subscriber: Callable[[_T], None]) None #
Allows for a subscriber to no longer receive actions from this signal instance.
- Parameters:
- subscriberCallable[[_T], None]
The subscriber, which took the result of the action from this signal instance.
- emit(value: _T) None #
Emits an action to its subscribers.
- Parameters:
- value_T
The result of an action taken.
- property is_silenced: bool#
Determines if this has been silenced.
- Returns:
- bool
If this has been silenced.
- link(signal_instance: SignalInstance[_T], converter: None = None, condition: collections.abc.Callable[[foundry.core.gui._T], bool] | None = None) None #
- link(signal_instance: SignalInstance[_U], converter: Callable[[_U], _T], condition: collections.abc.Callable[[foundry.core.gui._U], bool] | None = None) None
Links another signal instance to this signal instance.
- Parameters:
- signal_instanceSignalInstance[_U]
The other signal instance which is interested in this signal instance.
- converterCallable[[_T], _U] | None, optional
The converter required to understand the actions of this signal in terms of the provided signal instance, by default None
- conditionCallable[[_T], bool] | None, optional
The conditions required to forward_action this signal instance’s actions to the provided signal instance , by default None
- class SignalTester(signal: SignalInstance, count: int = 0)#
Bases:
object
A context manager for testing that a signal is emitted.
- Attributes:
- signal: SignalInstance
The signal to under test.
- count: int = 0
The amount of times the signal was called.
- signal: SignalInstance#
- class UndoRedo(model: _T, undo_stack: deque[Action[_T]] = NOTHING, redo_stack: deque[Action[_T]] = NOTHING)#
Bases:
Generic
[_T
]The concrete implementation of undoing and redoing actions.
- Parameters:
- Generic_T
The type of actions that are applied.
- Attributes:
- model: _T
The starting state of the controller.
- undo_stack: deque[Action[_T]] = Factory(lambda: deque(maxlen=1000000000))
A sequence of actions taken, which can be undone.
- redo_stack: deque[Action[_T]] = Factory(deque)
A sequence of undone actions, which can be reapplied.
- property can_redo: bool#
If there exists any actions that have been undone.
- Returns:
- bool
If any actions exist that can be redone.
- property can_undo: bool#
If model composed with undo_stack is equal to model.
- Returns:
- bool
If any actions exist that can be undone.
- do(action: Action[_T]) None #
Adds an action to the undo stack.
- Parameters:
- actionAction[_T]
The action performed.
- model: _T#
- redo() Callable[[], _T] #
Redoes the last action.
- Returns:
- Callable[[], _T]
The required action to be performed.
- slots = ('model', 'undo_stack', 'redo_stack', '_current_model')#
- class UndoRedoActor#
Bases:
_Object
[_T
]The bare bones implementation required for any component which desires to work inside an undo and redo system.
- Parameters:
- _Object_T
The type of the actions being performed.
- Attributes:
- __children__: Mapping[int, str]
A mapping of children and their associated name with respect to model.
- model: _T
The model of the actions being performed.
- _model_prior: _T
A hacky work-around to allow finding the prior state of a given system after an action has been performed, but before it has been applied to the undo and redo system.
- final compose_child_action(action: Action) Action[_T] #
Provides an action for this instance from a child’s action.
- Parameters:
- actionAction
The child action taken.
- Returns:
- Action[_T]
This instance’s action, which composed the child’s action.
- final get_child_attribute(actor: UndoRedoActor) str #
Determines the associated field of a child actor with respect to model.
- Parameters:
- actorUndoRedoActor
The child actor.
- Returns:
- str
The associated field for actor.
- class UndoRedoExtendedForwarder#
Bases:
UndoRedoHelper
[_T
],UndoRedoForwarder
[_T
]- property did_action: SignalInstance[Action[_T]]#
- initialize_state(model: _T, *args, **kwargs) None #
Required actions for an undo and redo controller on initialize_state up.
Notes
This does not use __init__ to be compatible with Object.
- class UndoRedoForwarder#
Bases:
UndoRedoActor
[_T
]An object inside an undo and redo system which seeks to forward_action its action and its children’s actions to another object to handle undo and redo logic.
- Parameters:
- UndoRedoActor_T
The type of the actions being performed.
- property action_performed: SignalInstance[Action[_T]]#
- change_state(model: _T) None #
Applies model to this instance.
- Parameters:
- model_T
The model to be applied.
- final do(model_prior: _T, model_after: _T, name: str = 'change_state') None #
Emits that an action has been performed.
- Parameters:
- model_prior_T
The prior state of the model.
- model_after_T
The new state of the model.
- name: str
The name of the action taken place, default ‘change_state’.
- final forward_action(action: Action[_T]) None #
Forwards a child’s action.
- Parameters:
- actionAction
The child’s action to be forwarded.
- link_child(child: UndoRedoForwarder) None #
Links a child to a parent, such that the parent can forward_action all child actions.
- Parameters:
- childUndoRedoForwarder
The child to be linked.
- class UndoRedoHelper#
Bases:
UndoRedoActor
[_T
]- property can_redo: bool#
If there exists any actions that have been undone.
- Returns:
- bool
If any actions exist that can be redone.
- property can_undo: bool#
If model composed with undo_stack is equal to model.
- Returns:
- bool
If any actions exist that can be undone.
- initialize_state(model: _T, undo_redo: Optional[UndoRedo[_T]] = None, *args, **kwargs) None #
Required actions for an undo and redo controller on initialize_state up.
Notes
This does not use __init__ to be compatible with Object.
- class UndoRedoRoot#
Bases:
UndoRedoHelper
[_T
],UndoRedoActor
[_T
]An object inside an undo and redo system which manages their own undo and redo stack.
- Parameters:
- UndoRedoActor_T
The type of the actions being performed.
- Attributes:
- __undo_redo__: UndoRedo[_T]
The internal undo and redo controller.
- change_state(model: _T) None #
Applies model to this instance.
- Parameters:
- model_T
The model to be applied.
- final do(action: Action[_T], *, apply_action: bool = False) None #
Adds an action to the undo stack.
- Parameters:
- actionAction[_T]
The action performed.
- apply_action: bool = False
If the action should be applied to the model.
- initialize_state(model: _T, *args, **kwargs) None #
Required actions for an undo and redo controller on initialize_state up.
Notes
This does not use __init__ to be compatible with Object.
- link_child(child: UndoRedoForwarder) None #
Links a child to a parent, such that the parent can undo and redo all child actions.
- Parameters:
- childUndoRedoForwarder
The child to be linked.
- final process_action(action: Action) None #
Processes an action performed by a child and puts it in terms of how to undo and redo it from this parent.
- Parameters:
- actionAction
The action performed.
foundry.core.icon module#
- class Icon#
Bases:
QIcon
,ConcreteValidator
,KeywordValidator
- classmethod validate(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
foundry.core.namespace module#
- class ArgumentsValidator#
Bases:
SingleArgumentValidator
A validator to more easily parse a list of arguments.
- class BoolValidator(value: Any)#
Bases:
ConcreteValidator
,SingleArgumentValidator
A validator for booleans.
Notes
Due to the way literals work inside Python, bool cannot be extended. To get around this restriction we simply decompose the validator to its core type.
- exception ChildDoesNotExistException(path: Path, unfound_child: str, parent: foundry.core.namespace.Namespace | None = None)#
Bases:
NamespaceValidationException
A method is called where the :class:~`foundry.core.namespace.Namespace.Namespace`_ did not have child when a child was required.
- Attributes:
- parent: Optional[Namespace]
The parent that did not contain
- path: Path
- unfound_child: str
- parent: foundry.core.namespace.Namespace | None#
- exception CircularImportException(cycle: tuple[foundry.core.namespace.Path] | None = None)#
Bases:
NamespaceValidationException
This exception is raised during the importation of dependencies if a cycle exists. A cycle makes it so none of the :class:~`foundry.core.namespace.Namespace`_ inside the cycle could be fully initialized without violating the invariant of the namespace. Thus, the namespaces cannot be initialized and this exception must be raised.
- Attributes:
- cycle: Optional[tuple[Path]]
The cycle that was detected.
- cycle: tuple[foundry.core.namespace.Path] | None#
- ComplexValidatorCallable#
Validates a type, _T into an object by accepting a map of values and a sequence and map of preset conditions required for a complex type validator.
alias of
Callable
[type
[_T
],Mapping
,Sequence
,Callable
[type
[_T
],Any
,_T
]]
- class ComplexValidatorCallableInformation(validator: Callable[[type[_T], Mapping, Sequence], Callable[[type[_T], Any], _T]], arguments: tuple[Any, ...] = NOTHING, keywords_arguments: Mapping[str, Any] = NOTHING, restrict_arguments: bool = True, restrict_keywords: bool = True)#
Bases:
_ComplexValidatorCallableInformation
[_T
]- decompose(*args, **kwargs) Callable[[type[_T], Any], _T] #
Decomposes the complex validator into a normal validator.
- Returns:
- ValidatorCallable
The decomposed validator.
Notes
This method does not supply any validation of the arguments passed.
- validate_type_information(info: TypeInformation) tuple[collections.abc.Sequence, collections.abc.Mapping] #
Validates a complex validator’s arguments, such that it can be safely decomposed with the arguments and keyword-arguments returned.
- Parameters:
- infoTypeInformation
The type arguments to validate.
- Returns:
- _ComplexValidatorArguments
The validated type arguments and keyword-arguments required to decompose self.
- Raises:
- InvalidPositionalArgumentsException
Positional arguments are missing or too many positional arguments were provided.
- InvalidKeywordArgumentsException
Keyword arguments are missing or extra keys were provided.
- TypeError
One of the positional arguments was formed into an invalid type.
- TypeError
One of the keyword arguments was formed into an invalid type.
Notes
If self does not set restrict_arguments, only the info of self will be validated. The rest of the positional arguments will be appended to the end not validated. The same process occurs for restrict_keywords.
- class ConcreteValidator#
Bases:
Validator
Automatically provides this class as the type suggestion for the handler. This is so the namespace generation functions can actually call this instance with the correct type.
- class property type_handler: TypeHandler[Self]#
Provides the type handler for this type.
- Returns:
- TypeHandler[Self]
The handler for to validate this type.
- DEFAULT_ARGUMENT: Literal['__DEFAULT_ARGUMENT__'] = '__DEFAULT_ARGUMENT__'#
When a validator only desires a single argument, it will be passed as through this.
- class DefaultValidator#
Bases:
OptionalValidator
A validator which decorates another type to allow it to either be provided or be a default value. Otherwise, it will provide normal validation of the underlying validator.
- classmethod generate_class(argument_validator: type[foundry.core.namespace.Validator], default: Any) type[foundry.core.namespace.Validator] #
Generates an default or optional validator which decorates the underlying validator provided.
- Parameters:
- argument_validatortype[Validator]
The validator to be decorated.
- Returns:
- type[Validator]
The default or optional validator that wraps argument_validator to have the default value of default.
- class FloatValidator(value: Any)#
Bases:
float
,PrimitiveValidator
A validator for floats.
- INVALID_USER_DEFINED_TYPES: str = '^(__)([^\r\n]+)(__)'#
Types that cannot be defined from the user. This is primarily dunder types.
- class IntegerValidator(value: Any)#
Bases:
int
,PrimitiveValidator
A validator for integers.
- exception InvalidChildName(name: str, invalid_element: str | None = None)#
Bases:
ValueError
An exception raised when a child’s name inside :class:~`foundry.core.namespace.util.ChildTreeProtocol`_ is considered to be invalid.
- Attributes:
- name: str
The invalid string in its entirety.
- invalid_element: str
The invalid portion of the string. By definition this must be a subset of name.
- exception InvalidKeywordArgumentsException(validator: ComplexValidatorCallableInformation, arguments: Mapping)#
Bases:
ValidationException
An exception that is raised during the validation of a validator which provided too many or few keyword arguments.
- arguments#
- validator#
- exception InvalidPositionalArgumentsException(validator: ComplexValidatorCallableInformation, arguments: Sequence)#
Bases:
ValidationException
An exception that is raised during the validation of a validator which provided too many or few positional arguments.
- arguments#
- validator#
- exception InvalidTypeArgumentException#
Bases:
ValidationException
An exception that is raised when arguments to define the type of an object to validate is not provided.
- Attributes:
- argument: Mapping
The argument that caused the exception.
- handler: _TypeHandler | _TypeHandlerManager
The handler that was unable to determine the type.
- argument: collections.abc.Mapping | str#
- handler: foundry.core.namespace._TypeHandler | foundry.core.namespace._TypeHandlerManager#
- class KeywordValidator#
Bases:
Validator
A validator to more easily parse a dict and their associated keyword arguments.
- classmethod check_for_kwargs_only(values: Any, *expected: tuple[str, bool]) Mapping #
A convenience method to ensure only key-word arguments are passed.
- Parameters:
- valuesAny
The arguments to validate.
- *expected: tuple[str, bool]
Any key-word arguments that are expected anf if they are required.
- Returns:
- Mapping
The validated arguments.
- Raises:
- MalformedArgumentsExceptions
If the arguments were invalid.
- MissingException
If an expected argument is not provided inside values.
- exception MalformedArgumentsExceptions(class_: type[foundry.core.namespace.Validator], expected_value: type, provided_value: Any)#
Bases:
ValidationException
An exception that is raised when the arguments and key-word arguments are incorrectly provided.
- class_#
- expected_value#
- provided_value#
- exception MissingException(class_: type[foundry.core.namespace.Validator], required_fields: set[str], provided_values: Mapping[str, Any])#
Bases:
ValidationException
- class_: type[foundry.core.namespace.Validator]#
- exception MissingTypeArgumentException(argument: Any, handler: foundry.core.namespace._TypeHandler | foundry.core.namespace._TypeHandlerManager)#
Bases:
InvalidTypeArgumentException
An exception that is raised when the type arguments are not provided.
- NOT_PROVIDED_ARGUMENT: Literal['__NOT_PROVIDED_ARGUMENT__'] = '__NOT_PROVIDED_ARGUMENT__'#
When the user did not provide an argument, this signifies that a default value should be used instead.
- class Namespace(parent: Namespace | None = None, dependencies: Mapping[str, Namespace] = NOTHING, elements: Mapping[str, _T] = NOTHING, children: Mapping[str, Namespace] = NOTHING, validators: _TypeHandlerManager = NOTHING)#
Bases:
Generic
[_T
]A complex tree structure to aid in the parsing of JSON and dictionary structures to facilitate the reuse of names and objects in different contexts.
- Parameters:
- _T
The type that each elements is inside this namespace.
- Attributes:
- parent: Namespace | None = None, optional
The parent namespace, which will contain this instance as a child. If None is provided, this namespace is assumed to be an orphan or a root node. By default, the namespace is a root node.
- dependencies: Mapping[str, Namespace] = {}, optional
A map of dependencies that were successfully loaded from this namespace’s parent, such that this namespace is self sufficient and does not need to interface with its parent. Primarily, this instance will not consider mutations, as it is assumed that a namespace is immutable. There path is also included, to allow for more complex operations. This is an optional field, if it is not provided it is assumed that there are no dependencies.
- elements: Mapping[str, _T] = {}, optional
A map of elements that represent this namespace’s core contribution. This represents the core mapping functionality of the namespace. By default there are no elements.
- children: Mapping[str, Namespace] = {}, optional.
A map of namespaces which depend on this namespace to instantiate. Children also often inherit many other attributes, such as validators and can relatively reference from the parent. By default a namespace contains no children.
- validators: _TypeHandlerManager = TypeHandlerManager({})
A manager for the various types that this namespace and its children can define without any external actions. This can be used to limit possible user action and to facilitate dependency injection opposed to statically defining every possible type and their associated validator. By default no types can be declared. This is a design decision to enforce limiting user input.
- dict() dict #
Converts the namespace to a dict that can be reconstructed back into itself.
- Returns:
- dict
A dict that represents a namespace.
- evolve_child(name: str, child: Namespace) Namespace #
A method to recursively generate a new namespace where a new child is appended to itself.
- Parameters:
- namestr
The name of the child to be appended.
- childNamespace
The child to be appended.
- Returns:
- Namespace
The root node of the parent namespace updated to reflect the parent namespace with the child appended.
Notes
Because a namespace is immutable, changing the children of a namespace would undermine the purpose of an immutable type after its construction. Because a namespace cannot be initialized with its children due to dependency conflicts, they must be added after its construction. To achieve this, a new root namespace must be generated to reflect this change in the tree structure of the namespaces.
- from_path(path: Path) Namespace #
Finds a namespace starting from this namespace by following the path provided.
- Parameters:
- pathPath
The path to follow to get to a namespace.
- Returns:
- Namespace
The namespace relative to this namespace and the path provided.
- Raises:
- KeyError
There does not exist a namespace relative to this namespace the path provided, such that :func:~`foundry.core.namespace.Namespace.namespace_exists_at_path`_ is False. Thus, a namespace cannot be returned from the parameters provided.
- property name: str#
Finds the name of the child inside its parent that refers to itself.
- Returns:
- str
The name that refers to itself from its parent.
- Raises:
- ParentDoesNotExistException
The parent of this instance is None.
- ParentDoesNotContainChildException
The parent and child are not linked properly.
- namespace_exists_at_path(path: Path) bool #
Checks if a namespace exists relative to this namespace and a provided path.
- Parameters:
- pathPath
The path the namespace is relative to.
- Returns:
- bool
If the namespace exists relative to this namespace and the path provided.
- parent: foundry.core.namespace.Namespace | None#
- property path: Sequence[str]#
Provides a series of names or keys that will yield itself from the root node.
- Returns:
- Sequence[str]
A series of names to provide itself from the root node.
- property public_elements: ChainMap#
The entire map of elements that can be accessed via the mapping interface.
- Returns:
- ChainMap
A map containing the elements of this instance and any public facing elements from its dependencies.
- property root: Namespace#
Finds the child tree without a parent. From the root node all other child tree of the same vein should be accessible.
- Returns:
- ExtendedChildTree
The namespace whose parent is None.
- validators: _TypeHandlerManager#
- exception NamespaceValidationException#
Bases:
ValidationException
An exception that is raised during the validation of a namespace.
- class NonNegativeIntegerValidator(value: Any)#
Bases:
IntegerValidator
- NoneValidator#
alias of
ConcreteValidator
- class OptionalValidator#
Bases:
ConcreteValidator
A validator which decorates another type to allow it to either be provided or be None. Otherwise, it will provide normal validation of the underlying validator.
- classmethod generate_class(argument_validator: type[foundry.core.namespace.Validator]) type[foundry.core.namespace.Validator] #
Generates an optional validator which decorates the underlying validator provided.
- Parameters:
- argument_validatortype[Validator]
The validator to be decorated.
- Returns:
- type[Validator]
The optional validator that wraps argument_validator.
- PARENT_ARGUMENT: Literal['__PARENT__'] = '__PARENT__'#
The parent namespace that is passed to create an object relating to its namespace.
- exception ParentDoesNotContainChildException(parent: Namespace, child: Namespace)#
Bases:
NamespaceValidationException
For each :class:~`foundry.core.namespace.Namespace.Namespace`, it is expected that the parent attribute also references the child. If a method which relies on this functionality does finds that this is not the case, this exception will be raised.
- Attributes:
- parent: Namespace
That does not have a reference to the child.
- child: Namespace
The child which called the method that required this functionality.
- exception ParentDoesNotExistException(child: foundry.core.namespace.Namespace | None = None)#
Bases:
NamespaceValidationException
A method is called where the :class:~`foundry.core.namespace.Namespace`_ did not have parent where a parent was required.
- Attributes:
- child: Optional[Namespace]
The child without a parent.
- child: foundry.core.namespace.Namespace | None#
- class Path(decomposed_path: tuple[str, ...] = NOTHING)#
Bases:
object
A representation of a path that be taken through a tree structure to get to a given element.
- Raises:
- InvalidChildName
If any of the children name are returned as invalid for
foundry.core.namespace.Path.is_valid_name()
.
- Attributes:
- decomposed_path: tuple[str, …] = (,)
A series of strings that represent a series of keys that can be taken to traverse a tree structure.
- create_child(name: str) Path #
Creates a child element with this instance as the parent and name as a child of parent.
- Parameters:
- namestr
A child of this path to create a new instance from.
- Returns:
- Path
A path that represents a child of this parent with the name as the top element.
- Raises:
- InvalidChildName
If name is returned as invalid for
foundry.core.namespace.Path.is_valid_name()
.
- classmethod create_child_from_parent(parent: foundry.core.namespace.Path | None, child: str) Path #
Create a child of the same instance of this from parent, if it exists, and a child. If no child exists, then the child will be created as root.
- Parameters:
- parentOptional[Path]
A parent that may exist to create a child from.
- childstr
The name of the top most name to exist inside the path.
- Returns:
- Self
A path that represents a child of the parent, if it exists, otherwise root.
- Raises:
- InvalidChildName
If name is returned as invalid for
foundry.core.namespace.Path.is_valid_name()
.
- classmethod from_string(s: str) Path #
Creates a path from a string.
- Parameters:
- sstr
The string to convert to a path.
- Returns:
- Self
A path that represents a path.
- Raises:
- InvalidChildName
If any of the children name are returned as invalid for
foundry.core.namespace.is_valid_name()
.
- static is_valid_name(name: Any, *, regex: str = '^[A-Za-z_][A-Za-z0-9_]*$') bool #
Determines if a name for a given child is considered valid.
- Parameters:
- nameAny
The name to check if it is valid.
- regexstr, optional
The regex expression to check for validity.
- Returns:
- bool
If the name is valid.
- property name: str#
Provides the name of the element referenced.
- Returns:
- str
The name of the element referenced.
- property parent: foundry.core.namespace.Path | None#
Provides the parent Path of this path, if one exists.
- Returns:
- Optional[Path]
The parent path of this path if one exists, else None.
- property root: str#
Provides the root of the element referenced.
- Returns:
- str
The root of the element referenced.
- classmethod validate(*_, path: str, use_parent: bool = True, parent: foundry.core.namespace.Namespace | None = None) Path #
Validates that the provided object is a valid Path.
- Parameters:
- pathstr
The path to be validated.
- use_parentbool, optional
If the path must exist relative to parent, by default True
- parentNamespace | None, optional
The namespace to validate the path from, by default None
- Returns:
- Path
Generates a validated path from s.
- Raises:
- ValueError
If use_parent and there does parent is None.
- TypeError
If parent is not None or a Namespace.
- classmethod validate_path_from_parent(parent: Namespace, s: str) Path #
Adds an additional validation that the path derived from s exists relative to parent.
- Parameters:
- parentNamespace
The parent to derive the path from.
- sstr
The path to be derived.
- Returns:
- Path
The path derived from s and parent.
- Raises:
- ValueError
The path s does not exist relative to parent.
- class PrimitiveValidator(value: Any)#
Bases:
ConcreteValidator
,SingleArgumentValidator
Adds methods to easily validate primitives through their native constructors.
- class SequenceValidator#
Bases:
ConcreteValidator
A validator which decorates another type to allow it to be provided as a list of elements.
- classmethod generate_class(argument_validator: type[_V]) type[foundry.core.namespace.Validator] #
Generates an sequence validator which decorates the underlying validator provided.
- Parameters:
- argument_validatortype[Validator]
The validator to be decorated.
- Returns:
- type[Validator]
The sequence validator that wraps argument_validator.
- class SingleArgumentValidator#
Bases:
Validator
A validator that only accepts a single validator.
- classmethod get_default_argument(v: Any) Any #
A convenience method to access the default argument for a type which only accepts a single argument.
- Parameters:
- vAny
A mapping containing the information to generate the object.
- Returns:
- Any
The default argument
- Raises:
- TypeError
Both the type and default argument is not present.
- TypeError
Too many arguments were provided to deduce the default argument.
- TypeError
No argument were provided other than the type.
- class StringValidator(value: Any)#
Bases:
str
,PrimitiveValidator
A validator for strings.
- TYPE_INFO_ARGS_ARGUMENTS: Literal['__TYPE_INFO_ARGS__'] = '__TYPE_INFO_ARGS__'#
The key inside a dictionary for determining extra arguments for a type.
- TYPE_INFO_ARGUMENT: Literal['__TYPE_INFO_ARGUMENT__'] = '__TYPE_INFO_ARGUMENT__'#
The type the validator that should be used to create and object.
- TYPE_INFO_ARGUMENTS = ('__TYPE_INFO_ARGUMENT__', 'TYPE', 'type')#
The valid ways a user can define the type attribute.
- TYPE_INFO_KWARGS_ARGUMENTS: Literal['__TYPE_INFO_KWARGS__'] = '__TYPE_INFO_KWARGS__'#
The key inside a dictionary for determining extra keyword arguments for a type.
- class TupleValidator#
Bases:
ConcreteValidator
A validator which decorates a series of validators to allow it to be provided as a ordered list of elements.
- classmethod generate_class(argument_validators: tuple[type[foundry.core.namespace.Validator], ...]) type[foundry.core.namespace.Validator] #
Generates an tuple validator which decorates the underlying validators provided.
- Parameters:
- argument_validators: tuple[type[Validator], …]
An ordered sequence of validators to be decorated.
- Returns:
- type[Validator]
The tuple validator that wraps argument_validators.
- class TypeHandler(types: Mapping[str, collections.abc.Callable[[type[_T], Any], foundry.core.namespace._T] | foundry.core.namespace.ValidatorCallableInformation | foundry.core.namespace._ComplexValidatorCallableInformation] = NOTHING, default_type_suggestion: type[_T] | None = None, default_validator: foundry.core.namespace.TypeInformation | None = None)#
Bases:
_TypeHandler
[_T
]A model for representing the possible types a namespace element can possess and their respective validator methods.
- Parameters:
- Generic_T
The type to be validated to.
- Attributes:
- types: ValidatorMapping
A map containing the types and their respective validator methods. This can come in two variants. It can either be a simple callable or be defined as a ValidatorCallableInformation. If a callable is provided, it will automatically be converted to a ValidatorCallableInformation with default parameters for any ValidatorCallableInformation specific methods. For more specification a ValidatorCallableInformation should be used instead.
- default_type_suggestion: Type[_T] | None, optional
The suggested type to generate the handler as. If not provided, no assumption should be made.
- get_if_validator_uses_parent(type: TypeInformation) bool #
Gets if a validator should request the parent namespace to be inside the map which is passed to it for its initialization.
- Parameters:
- typestr
The type to validate.
- Returns:
- bool
If the parent is used by the validator.
- get_type_suggestion(info: TypeInformation) type[_T] | None #
Provides the type that info requires as the first argument for its validator.
- Parameters:
- infoTypeInformation
The information for a given type to generate its associated validator.
- Returns:
- type[_T] | None
Provides the type if one is provided, otherwise defaults on default_type_suggestion.
- get_validator(type: TypeInformation) Callable[[type[_T], Any], _T] #
Gets a validator to generate a specific object from a map.
- Parameters:
- typeTypeInformation
The type information that defines the validator.
- Returns:
- ValidatorCallable
The validator associated with type.
Notes
If type does not define parent, then complex validators will not be supported.
- has_type(type: TypeInformation) bool #
A convenience method to quickly determine if a ‘type’ is valid.
- Parameters:
- typeTypeInformation
The type to check if it is registered.
- Returns:
- bool
If the type is registered.
- overwrite_from_parent(other: _TypeHandler) Self #
other overwrites or adds additional type validators from this handler to form a new handler.
- Parameters:
- other_TypeHandler
The handler to override values from this handler.
- Returns:
- Self
The extended parent.
- classmethod validate_to_type(type: TypeInformation, values: Mapping) _T #
Generates and validates values of type to generate an object from parent.
- Parameters:
- typeTypeInformation
The type of object to generate and validate.
- valuesMapping
The attributes of the object.
- Returns:
- _T
The generated and validated object.
- Raises:
- TypeError
parent was not provided inside type.
- class TypeHandlerManager(types: Mapping[str, _TypeHandler] = NOTHING)#
Bases:
_TypeHandlerManager
Manages which type is associated to which handler. This primarily serves as a series of convenience methods to manage a map to ensure consistent validation.
- Attributes:
- types: ValidatorHandlerMapping
A series of types and their associated validator handler.
- add_type_handler(type_: str, handler: _TypeHandler) Self #
Generates a new manager which adds a handler to validate type_. If type_ is already defined a new handler will be used which overrides this instance’s handler for type_, such that handler’s validators will be used instead.
- Parameters:
- type_str
The type to add validators to.
- handler_TypeHandler
The handler to validate the type with.
- Returns:
- Self
The generated manager with the mutation or addition to type_.
- classmethod from_managers(*managers: _TypeHandlerManager) Self #
Effectively merges a series of managers together into a single manager.
- Parameters:
- *managers: _TypeHandlerManager
A series of managers to merge together.
- from_select_types(*types: str) Self #
Generates a new manager which ensures only types can be validated.
- Parameters:
- *types: str
The types that can be validated.
- Returns:
- Self
This manager, but with a limit to only validate types.
- override_type_handler(type_: str, handler: _TypeHandler) Self #
Generates a new manager which removes the current handler of type_ if it exists and replaces it with handler.
- Parameters:
- type_str
The type to override.
- handler_TypeHandler
The handler to validate the type with.
- Returns:
- Self
The generated manager with the mutation or addition to type_.
- class TypeInformation(type_suggestion: str, arguments: tuple[Any, ...] = NOTHING, keyword_arguments: Mapping[str, Any] = NOTHING, parent: Namespace | None = None)#
Bases:
Generic
[_T
]A generic interface to represent a complex type.
- Parameters:
- type_suggestion: str
The name of the type to be identified.
- arguments: tuple[Any, …], default ()
The required arguments to pass to the type validator.
- keyword_arguments: Mapping[str, Any], default {}
The required keyword arguments to pass to the type validator.
- parent: Namespace | None = None
The parent of the type, if provided.
- parent: foundry.core.namespace.Namespace | None#
- exception TypeNotFoundException(argument: collections.abc.Mapping | str, handler: foundry.core.namespace._TypeHandler | foundry.core.namespace._TypeHandlerManager)#
Bases:
InvalidTypeArgumentException
An exception that is raised when the type argument is provide but the handler did not define the type provided.
- class TypeValidator(types: Mapping[str, collections.abc.Callable[[type[_T], Any], foundry.core.namespace._T] | foundry.core.namespace.ValidatorCallableInformation | foundry.core.namespace._ComplexValidatorCallableInformation] = NOTHING, default_type_suggestion: type[_T] | None = None, default_validator: foundry.core.namespace.TypeInformation | None = None)#
Bases:
ConcreteValidator
,KeywordValidator
,TypeHandler
A validator to generate a meta validator.
- classmethod from_validator(validator: type[foundry.core.namespace.Validator], parent: Namespace) Self #
- VALID_META_TYPE_ARGUMENTS = ('__TYPE_INFO_ARGS__', 'args', 'ARGS', 'arguments', 'ARGUMENTS')#
The valid ways a user can define the type meta-arguments.
- VALID_META_TYPE_KEYWORD_ARGUMENTS = ('__TYPE_INFO_KWARGS__', 'kwargs', 'KWARGS', 'keyword arguments', 'KEYWORD ARGUMENTS')#
The valid ways a user can define the type meta-keyword-arguments.
- exception ValidationException#
Bases:
ValueError
An exception that is raised during the validation of a validator.
- class Validator#
Bases:
_ValidatorHelper
A namespace element validator, which seeks to encourage extension and modularity for namespace validators.
Notes
While __allowed_conversions__ can be used in many applications, it is strongly advised to not use it unless absolutely required. This is because this creates the issue that any of the types provided from this validator will decompose into the union of all the types and this type provided. This could generate a leak of type data and would result in the corruption of validated data.
- Attributes:
- __validator_handler__: ClassVar[_TypeHandler]
The handler for validators to automatically validate and generate the objects from a namespace, also incorporates the parent’s attribute, if it exists.
- __type_default__: ClassVar[TypeInformation | None]
The type default. If None, then the type must be provided.
- __names__: ClassVar[tuple[str, …]]
The names to associate this type with.
- __required_validators__: ClassVar[tuple[type[Validator]]]
Required validators to use the full capacity of this validator.
- __allowed_conversions__: ClassVar[tuple[type, …]] = ()
Any additional acceptable conversions other than this validator that this validator is permitted to create. This is meant to used to reference an underlying validator which this type decorates.
- class property default_name: str#
Provides the name suggestion for this type, for it to be found by a manager.
- Returns:
- str
The name suggestion.
- classmethod get_type_handler_from_parent(parent: Namespace) _TypeHandler #
Obtains the handler for a type from parent.
- Parameters:
- parent: Namespace
The parent to get the handler from.
- Returns:
- _TypeHandler
The handler that is associated with this type.
- class property type_handler: TypeHandler[Self]#
Provides the type handler for this type.
- Returns:
- TypeHandler[Self]
The handler for to validate this type.
- class property type_manager: TypeHandlerManager#
Provides the type manager for this type and all of its associated names.
- Returns:
- TypeHandlerManager
The manager to find the proper validations for this type.
- classmethod validate_arguments_to_map(v: Any, *, default_override: foundry.core.namespace.TypeInformation | None = None, parent: foundry.core.namespace.Namespace | None = None) dict #
Standardizes the arguments passed to a map.
- Parameters:
- vAny
A map containing the information to generate the object.
- default_override: TypeInformation | None = None
An override to use as a default validator.
- parent: Namespace | None = None
Sets the parent attribute.
- Returns:
- Mapping
The information standardized to a map.
- Raises:
- TypeError
v was not passed as a map.
- classmethod validate_by_type(v: Mapping) Self #
Generates and validates an object by its type defined in __validator_handler__.
- Parameters:
- vMapping
A mapping containing the information to generate the object.
- Returns:
- Self
The object generated from v specified by its type.
- static validate_from_namespace(class_: type[_V], v: Mapping) _V #
Generates and validates from another existing object inside a namespace.
- Parameters:
- class_Type[_V]
The type to find inside the namespace.
- vMapping
A map containing a parent, name, and path.
- Returns:
- _V
The object inside the Namespace.
- Raises:
- TypeError
There does not exist a parent inside v
- TypeError
The parent is not a Namespace.
- TypeError
There does not exist a name inside v
- TypeError
The name is not a string.
- TypeError
There does not exist a path inside v
- TypeError
The path is not a string.
- classmethod validate_type(v: Any) Self #
Generates and validates an object by its types and ensures that there is a type inside v such that it can be validated further.
- Parameters:
- vAny
A map containing the information to generate the object.
- Returns:
- Self
The object generated from v specified by its type.
- Raises:
- TypeError
There does not exist type inside v and __type_default__ is None.
- TypeError
type is not a valid type.
- ValidatorCallable#
Validates a type _T into an object _T by accepting a map of values.
- class ValidatorCallableInformation(validator: Callable[[type[_T], Any], _T], type_suggestion: type[_T] | None = None, use_parent: bool = True)#
Bases:
Generic
[_T
]A generic interface to validate an type into an object.
- Attributes:
- validator: ValidatorCallable
The callable to convert the type into an object.
- type_suggestion: Type[_T] | None = None
The suggested type to convert.
- use_parent: bool = True
If the type requires a parent namespace to become an object.
- ValidatorHandlerMapping#
A map which contains a series of string, which define creatable types such as an int, float, str; and their respective handlers such that they can be further validated into that type.
- ValidatorInformation = collections.abc.Callable[[type[~_T], typing.Any], ~_T] | foundry.core.namespace.ValidatorCallableInformation | foundry.core.namespace._ComplexValidatorCallableInformation#
All the possible variants of validator callable information that can be provided from a namespace.
- ValidatorMapping#
A map which contains a series of strings, which define creatable types such as the default, from namespace, etc.; and their respective validators such that types could be validated in multiple ways.
alias of
Mapping
[str
,Callable
[type
[_T
],Any
,_T
] |ValidatorCallableInformation
|_ComplexValidatorCallableInformation
]
- custom_validator(validator_name: str, complex: bool = False, use_parent: bool | None = None, validator: collections.abc.Callable[[type[_T], Any], foundry.core.namespace._T] | foundry.core.namespace.ValidatorCallableInformation | foundry.core.namespace._ComplexValidatorCallableInformation | None = None, method_name: str = 'validate') Callable[[type[_V]], type[_V]] #
Provides a decorator to add a custom method as a validator to a validator type.
- Parameters:
- validator_namestr
The name that the user can define this validator as.
- complex: bool, optional
Determines if the validator provided should be considered complex if it derives from cls and method_name.
- use_parent
If the validator should use a parent.
- validatorValidatorInformation | None, optional
The method to be used as the validator, by default None. If None, it will try to use method_name to find a classmethod to use as a validator.
- method_namestr, optional
A method_name to provide if a method is not provided, by default “validate”
- Returns:
- Callable[[type[_V], ValidatorInformation | None, str], type[_V]]
A decorator to add a custom method to a validator.
- default_validator(cls: None = None, complex: bool = False, use_parent: bool = True, validator: collections.abc.Callable[[type[_T], Any], foundry.core.namespace._T] | foundry.core.namespace.ValidatorCallableInformation | foundry.core.namespace._ComplexValidatorCallableInformation | None = None, method_name: str = 'validate') partial #
- default_validator(cls: type[_V] = None, complex: bool = False, use_parent: bool = True, validator: collections.abc.Callable[[type[_T], Any], foundry.core.namespace._T] | foundry.core.namespace.ValidatorCallableInformation | foundry.core.namespace._ComplexValidatorCallableInformation | None = None, method_name: str = 'validate') type[_V]
Generates a validator for the default type suggestion.
- Parameters:
- clstype[_V]
The validator to decorate.
- complex: bool, optional
If the validator is complex.
- use_parent
If the validator should use a parent.
- validatorValidatorInformation | None, optional
The validator to use, if it is not defined inside cls, by default None
- method_namestr, optional
The method of the cls to use if validator is None, by default “validate”
- find_cycle(graph: Mapping[Path, set[foundry.core.namespace.Path]]) tuple[foundry.core.namespace.Path] #
Determines if there is a cycle inside for any dependency from a mapping.
- Parameters:
- graphMapping[Path, set[Path]]
The graph to test if a cycle exists.
- Returns:
- tuple[Path]
A path which creates the cycle.
- generate_dependency_graph(name: str, v: Mapping, parent: foundry.core.namespace.Path | None = None) Mapping[Path, set[foundry.core.namespace.Path]] #
Generates a graph where each vertex is a namespace and its neighbors are its dependencies, including its parent.
- Parameters:
- name: str
The name of the root node.
- vMapping
A map structure that represents the data.
- parentOptional[Path], optional
The parent of the root node, by default None
- Returns:
- Mapping[Path, set[Path]]
The graph that represents the data supplied.
- generate_namespace(v: Mapping, validators: foundry.core.namespace._TypeHandlerManager | None = None) Namespace #
Generates the root namespace from a mapping, creating every aspect of the namespace, including its children. This also includes validation of the namespace, its children, its elements, and its children’s elements, recursively.
- Parameters:
- vMapping
The mapping to generate the namespace and its children from.
- validators: _TypeHandlerManager | None, optional.
The possible validators that the namespace can possess, None by default.
- Returns:
- Namespace
The root namespace and its children derived from the map provided.
Notes
Generating namespace is a multi-step process because a namespace’s children can depend on components which depend on it’s parent. In other words, a child cannot be guaranteed to be able to be initialized at the time that it’s parent is created. Instead, the child must be appended afterwards to ensure that the parent namespace can accommodate all the variants that its children can take. Because a namespace’s dependency and parent must follow a directed acyclic graph with accordance to the namespace’s invariant, we can sort the dependency graph of the root topographically. This generates a sequence which can load the all the namespaces in an order which will not conflict with one another. Once every namespace is iterated through in topographic order, the root should correctly define the map.
- get_namespace_dict_from_path(v: Mapping, path: Path) Mapping #
Provides the mapping associated with a given path that will generate a namespace.
- Parameters:
- vMapping
The root map and its children to obtain its or its children’s namespace’s map from.
- pathPath
The path to namespace which is valid from root.
- Returns:
- Mapping
The namespace’s map associated with the path provided.
- Raises:
- ChildDoesNotExistException
The child associated with the path provided does not exist inside the map.
- sort_topographically(graph: Mapping[Path, set[foundry.core.namespace.Path]]) Iterable[Path] #
From a graph of dependencies an iterable is produced to sort the vertices in topographic order, such that the dependencies could be loaded sequentially without any exceptions.
- Parameters:
- graphMapping[Path, set[Path]]
The representation of the graph, where the mapping represents the set of vertices and its respective neighbors.
- Returns:
- Iterable[Path]
An iterable of the paths for the respective namespaces.
- validate(**kwargs: type[foundry.core.namespace.Validator]) Callable[[Callable[[...], _KV]], Callable[[type[_KV], Any], _KV]] #
A decorator to automatically validate a series of keyword arguments with a series of validators.
- Parameters:
- **kwargs: type[Validator]
A series of keyword required values to generator with respect to the validator.
- Returns:
- Callable[[Callable[…, _KV]], ValidatorCallable[_KV]]
A decorator which will take a classmethod and converts it to a validator.
- validate_argument(validator: type[_V], arg: Any, parent: Namespace) _V #
Validates an arbitrary argument where the validator is already known.
- Parameters:
- validatortype[_V]
The type to validate to.
- argAny
The argument to be validated.
- parentNamespace
The parent to obtain validation information from.
- Returns:
- _V
The validated argument.
- validate_element(parent: Namespace, name: str, type: type[_T]) _T #
Validates a referenced element inside of a namespace to ensure that it exists and is of the correct type.
- Parameters:
- parent: Namespace
The namespace which the element of key name should exist inside.
- name: str
The index or key associated inside parent of the element.
- type_: Type[_T]
The type the element should take.
- Returns:
- _T
The element indexed inside parent with a key of name.
- Raises:
- ValueError
If the name is not a valid name for an element.
- ValueError
If there does not exist an element inside parent at name.
- ValueError
If the element inside parent at name is not of type_.
- validate_element_to_type(name: str, parent: Namespace, type_: type[_T]) type[_T] #
Validates that the element is of type_.
- Parameters:
- namestr
The name to of the element to validate.
- parentNamespace
The namespace to start the name from.
- type_Type[_T]
The expected type of the element.
- Returns:
- Type[_T]
The type used to validate the element.
- Raises:
- ValueError
The element was not of type_.
- validate_name_is_in_namespace(name: str, parent: Namespace) str #
Validates that name exists inside parent.
- Parameters:
- namestr
The name to validate.
- parentNamespace
The namespace to start the name from.
- Returns:
- str
The validated name.
- Raises:
- ValueError
If there does not exist an element at name inside parent.
- validate_namespace(v: Mapping, parent: foundry.core.namespace.Namespace | None = None, validators: foundry.core.namespace._TypeHandlerManager | None = None) Namespace #
Handles the primary validation which is required to generate a namespace. Specifically, its dependencies and it’s elements are validated and loaded into the namespace.
- Parameters:
- vMapping
The mapping to generate the namespace from.
- parentOptional[Namespace], optional
The parent of this namespace, by default makes the namespace the root.
- type_handler: _TypeHandlerManager | None, optional
The type manager to validate and generate new namespaces from, by default the parent’s handler if a parent is provided, otherwise the default handler will be used.
- Returns:
- Namespace
The namespace represented by this map, excluding its children.
- Raises:
- ChildDoesNotExistException
If a root node contains dependencies, it will raise an exception to note this contradiction. A root node may not depend on anything, by definition.
Notes
This method does not handle the generation of a namespace’s children. This is done intentionally because this namespace’s children may depend on namespace’s which depend on it’s parent. Thus, the parent cannot load its children without creating a circular importation loop. Instead, the children must be appended to the namespace after its initialization to facilitate such a relationship.
- validate_namespace_type(namespace: Namespace, v: Mapping) TypeInformation #
Validates that a namespace’s type is a valid type.
- Parameters:
- namespaceNamespace
The namespace to validate the type from.
- vMapping
The mapping with the data for a namespace.
- Returns:
- str
The validated type.
- Raises:
- TypeError
There does not exist type inside v.
- TypeError
type is not present inside validators.
- validate_path_name(path: Any) str #
Validates that the path can form a :class:~`foundry.core.namespace.Path`.
- Parameters:
- pathAny
The path to validate.
- Returns:
- str
The validated path.
- Raises:
- TypeError
If the path is not a string.
- ValueError
If the path cannot form a :class:~`foundry.core.namespace.Path`_ as specified by
- :func:~`foundry.core.namespace.is_valid_name`.
foundry.core.palette module#
- class Color(red: int, green: int, blue: int, alpha: int = 255)#
Bases:
ConcreteValidator
,KeywordValidator
A representation of a the spectral light perceived. The commonplace representation is RGBA, (red, green, blue, and alpha). There are also alternative representations supported, such as HSV (hue, saturation, and value).
- Attributes:
- red: int
An integer between 0 and 255 that represents the proportion of red to use.
- green: int
An integer between 0 and 255 that represents the proportion of green to use.
- blue: int
An integer between 0 and 255 that represents the proportion of blue to use.
- alpha: int
An integer between 0 and 255 that represents how transparent the color is.
- hue: int
An integer between 0 and 359 that represents the hue of the color.
- saturation: int
An integer between 0 and 255 that represents the saturation of the color.
- value: int
An integer between 0 and 255 that represents the value of the color.
- r: float
A float between 0.0 and 1.0 that represents the proportion of red to use.
- g: float
A float between 0.0 and 1.0 that represents the proportion of green to use.
- b: float
A float between 0.0 and 1.0 that represents the proportion of blue to use.
- a: float
A float between 0.0 and 1.0 that represents how transparent the color is.
- h: float
A float between 0.0 and 1.0 that represents the hue of the color.
- s: float
A float between 0.0 and 1.0 that represents the saturation of the color.
- v: float
A float between 0.0 and 1.0 that represents the value of the color.
- property a: float#
The proportion of how transparent the color is.
- Returns:
- float
A float between 0.0 and 1.0 that represents how transparent the color is.
- property b: float#
The proportion of blue inside the color.
- Returns:
- float
A float between 0.0 and 1.0 that represents the proportion of blue to use.
- classmethod from_hsv(hue: float, saturation: float, value: float) Self #
Generates a color from a hue, saturation, and value.
- Parameters:
- huefloat
The hue of the color.
- saturationfloat
The saturation of the color.
- valuefloat
The value of the color.
- Returns:
- Self
The RGBA representation of the color.
- property g: float#
The proportion of green inside the color.
- Returns:
- float
A float between 0.0 and 1.0 that represents the proportion of green to use.
- property h: float#
The hue of the color.
- Returns:
- float
A float between 0.0 and 1.0 that represents the hue of the color.
- property hue: int#
The hue of the color.
- Returns:
- int
An integer between 0 and 359 that represents the hue of the color.
- property r: float#
The proportion of red inside the color.
- Returns:
- float
A float between 0.0 and 1.0 that represents the proportion of red to use.
- property s: float#
The saturation of the color.
- Returns:
- float
A float between 0.0 and 1.0 that represents the saturation of the color.
- property saturation: int#
The saturation of the color.
- Returns:
- int
An integer between 0 and 255 that represents the saturation of the color.
- to_qt() QColor #
- property v: float#
The value of the color.
- Returns:
- float
A float between 0.0 and 1.0 that represents the value of the color.
- classmethod validate(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
- class ColorPalette(colors: ColorSequence)#
Bases:
ConcreteValidator
,KeywordValidator
A representation of a series of colors.
- colors: ColorSequence#
- count(value: foundry.core.palette.Color | PySide6.QtGui.QColor) int #
- index(value: foundry.core.palette.Color | PySide6.QtGui.QColor, start: int = 0, stop: int | None = None) int #
- classmethod validate_from_colors(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
- classmethod validate_from_default(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
- classmethod validate_from_json_file(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
- classmethod validate_from_palette_file(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
- class ColorSequence(iterable: Iterable[foundry.core.palette.Color | PySide6.QtGui.QColor])#
Bases:
Sequence
- count(value) integer -- return number of occurrences of value #
- index(value[, start[, stop]]) integer -- return first index of value. #
Raises ValueError if the value is not present.
Supporting start and stop arguments is optional, but recommended.
- class Palette(color_indexes: tuple[int, ...], color_palette: ColorPalette = ColorPalette(colors=ColorSequence([Color(red=120, green=128, blue=132, alpha=255), Color(red=0, green=0, blue=252, alpha=255), Color(red=0, green=0, blue=196, alpha=255), Color(red=64, green=40, blue=196, alpha=255), Color(red=148, green=0, blue=140, alpha=255), Color(red=172, green=0, blue=40, alpha=255), Color(red=172, green=16, blue=0, alpha=255), Color(red=140, green=24, blue=0, alpha=255), Color(red=80, green=48, blue=0, alpha=255), Color(red=0, green=120, blue=0, alpha=255), Color(red=0, green=104, blue=0, alpha=255), Color(red=0, green=88, blue=0, alpha=255), Color(red=0, green=64, blue=88, alpha=255), Color(red=0, green=0, blue=0, alpha=255), Color(red=0, green=0, blue=0, alpha=255), Color(red=0, green=0, blue=8, alpha=255), Color(red=188, green=192, blue=196, alpha=255), Color(red=0, green=120, blue=252, alpha=255), Color(red=0, green=136, blue=252, alpha=255), Color(red=104, green=72, blue=252, alpha=255), Color(red=220, green=0, blue=212, alpha=255), Color(red=228, green=0, blue=96, alpha=255), Color(red=252, green=56, blue=0, alpha=255), Color(red=228, green=96, blue=24, alpha=255), Color(red=172, green=128, blue=0, alpha=255), Color(red=0, green=184, blue=0, alpha=255), Color(red=0, green=168, blue=0, alpha=255), Color(red=0, green=168, blue=72, alpha=255), Color(red=0, green=136, blue=148, alpha=255), Color(red=44, green=44, blue=44, alpha=255), Color(red=0, green=0, blue=0, alpha=255), Color(red=0, green=0, blue=0, alpha=255), Color(red=252, green=248, blue=252, alpha=255), Color(red=56, green=192, blue=252, alpha=255), Color(red=104, green=136, blue=252, alpha=255), Color(red=156, green=120, blue=252, alpha=255), Color(red=252, green=120, blue=252, alpha=255), Color(red=252, green=88, blue=156, alpha=255), Color(red=252, green=120, blue=88, alpha=255), Color(red=252, green=160, blue=72, alpha=255), Color(red=252, green=184, blue=0, alpha=255), Color(red=188, green=248, blue=24, alpha=255), Color(red=88, green=216, blue=88, alpha=255), Color(red=88, green=248, blue=156, alpha=255), Color(red=0, green=232, blue=228, alpha=255), Color(red=96, green=96, blue=96, alpha=255), Color(red=0, green=0, blue=0, alpha=255), Color(red=0, green=0, blue=0, alpha=255), Color(red=252, green=248, blue=252, alpha=255), Color(red=164, green=232, blue=252, alpha=255), Color(red=188, green=184, blue=252, alpha=255), Color(red=220, green=184, blue=252, alpha=255), Color(red=252, green=184, blue=252, alpha=255), Color(red=244, green=192, blue=224, alpha=255), Color(red=244, green=208, blue=180, alpha=255), Color(red=252, green=224, blue=180, alpha=255), Color(red=252, green=216, blue=132, alpha=255), Color(red=220, green=248, blue=120, alpha=255), Color(red=184, green=248, blue=120, alpha=255), Color(red=176, green=240, blue=216, alpha=255), Color(red=0, green=248, blue=252, alpha=255), Color(red=200, green=192, blue=192, alpha=255), Color(red=0, green=0, blue=0, alpha=255), Color(red=0, green=0, blue=0, alpha=255)])))#
Bases:
ConcreteValidator
,KeywordValidator
- classmethod as_empty() Self #
Makes an empty palette of default values.
- Returns:
- AbstractPalette
A palette filled with default values.
- color_palette: ColorPalette#
- classmethod from_rom(address: int) Self #
Creates a palette from an absolute address in ROM.
- Parameters:
- addressint
The absolute address into the ROM.
- Returns:
- AbstractPalette
The palette that represents the absolute address in ROM.
- index(value: int | foundry.core.palette.Color | PySide6.QtGui.QColor) int #
- classmethod validate_from_colors(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
- classmethod validate_from_rom_address(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
- class PaletteGroup(palettes: tuple[foundry.core.palette.Palette])#
Bases:
ConcreteValidator
,KeywordValidator
A concrete implementation of a hashable and immutable group of palettes.
- classmethod as_empty() Self #
Makes an empty palette group of default values.
- Returns:
- AbstractPaletteGroup
The palette group filled with default values.
- property background_color: QColor#
- classmethod from_rom(address: int) Self #
Creates a palette group from an absolute address in ROM.
- Parameters:
- addressint
The absolute address into the ROM.
- Returns:
- AbstractPaletteGroup
The palette group that represents the absolute address in ROM.
- classmethod from_tileset(tileset: int, index: int) Self #
Loads a palette group from a tileset with a given index.
- Parameters:
- tilesetint
The index of the tileset.
- indexint
The index of the palette group inside the tileset.
- Returns:
- PaletteGroup
The PaletteGroup that represents the tileset’s palette group at the provided offset.
- classmethod validate(values: Any) _KV #
Validates values by the predetermined kwargs validator suggestions with respect to the parent namespace passed inside values.
- Parameters:
- valuesAny
A series of values to be validated.
- Returns:
- _KV
The values validated and composed into its correct type.
- Raises:
- KeyError
The parent namespace was not defined inside values.
foundry.core.redux_store module#
Defines a simple Redux store interface for Python.
This store takes in a default state on initialization rather than generating one internally. If it is desired to have one created interally, use a factory method.
A Generic type state S is used to hold the state data for the module and actions given to the store are used to transform the state into a new state through a set of reducers. The reducers are UI specific and so abstract in this interface definition.
- class Action(type: str, payload: Any)#
Bases:
object
User action that will be dispatched to the store for processing
type: str - a unique id that defines what action is happening payload: Any - the data payload of the action, can be Any type.
- class ReduxStore(state: S)#
-
An abstract Redux store for handing system state and user actions.
Redux is a pattern used for handing system state storage/change based on user interaction. More information can be found here: https://redux.js.org/introduction/core-concepts
The basic principle is that the store hold the system state and accepts user actions and creates a new system state based on that action.
Actions are dispatched to the store and the store will notify all subscribers if the state changes.
In this implementation the state is a generic type ‘S’ to be defined by the developer.
- dispatch(action: Action)#
Updates the system state based on user action.
The dispatch() routine takes in a user action and updates the current state by sending it to any reducers in the system and then notifies any subscribers to the store if the state has changed as a result of the action.
- get_default_state() S #
Returns the default state.
- get_state() S #
Get a copy of the current state.
- subscribe(subscriber)#
Subscribe a function to be called when the state changes.
foundry.core.tasks module#
- AUTOMATED_REMOVAL_DURATION: float = 5#
The amount of seconds the task manager will wait without any response from the parent process until it will automatically stop itself and terminate gracefully.
they won’t be burdened with unnecessary processing. During testing, PyTest does not end the process until all processes finish, so testing does not require a SEGKILL signal to end the testing. Also, it likely it also provides redundancy in killing the process.
- class DilledConnection(connection: _ConnectionBase)#
Bases:
_ConnectionBase
Decorates a connection object to use dill instead of pickle so we can serialize additional objects.
- close()#
Close the connection
- property closed#
True if the connection is closed
- fileno()#
File descriptor or handle of the connection
- poll(timeout=0.0)#
Whether there is any input available to be read
- property readable#
True if the connection is readable
- recv()#
Receive a (picklable) object
- recv_bytes(maxlength=None)#
Receive bytes data as a bytes object.
- recv_bytes_into(buf, offset=0)#
Receive bytes data into a writeable bytes-like object. Return the number of bytes read.
- send(obj)#
Send a (picklable) object
- send_bytes(buf, offset=0, size=None)#
Send the bytes data from a bytes-like object
- property writable#
True if the connection is writable
- FORCE_KILL_TIMEOUT: float = 0.1#
The amount of time a task manager is willing to wait on its workers to terminate if a kill signal is sent.
- FORCE_TERMINATION_TIMEOUT: float = 0.5#
The amount of time a terminating task manager is willing to wait on its workers to terminate.
- class FinishedTask(identity: int, result: Optional[_T], exception: Exception | None = None)#
Bases:
Generic
[_T
]A receipt of a finished task.
- Attributes:
- identity: int
The identity of the task completely.
- result: _T | None
The result of the task completed. If None is returned, it is implied an exception occurred.
- exception: Exception | None = None
An exception that was raised during the completion of a task, None if there does not exist.
- classmethod as_exception(identity: int, exception: Exception)#
Generates a finished task for an exception.
- Parameters:
- identity: int
The identity of the task completely.
- exception: Exception | None = None
An exception that was raised during the completion of a task.
- Returns:
- Self
The finished task that raised an exception.
- exception NotAPickleException#
Bases:
ValueError
- RESPONSIVE_TIMEOUT: float = 0.1#
The maximum amount of time a responsive task should take without getting timed out.
- class Replier(request: RequestPipe[RequestValue, ReplyValue])#
Bases:
Generic
[RequestValue
,ReplyValue
]An abstraction of a child process to facilitate the responses between its parent.
- Attributes:
- request: RequestPipe[RequestValue, ReplyValue]
An object to transmit data between processes.
- property received_request: SignalInstance[RequestValue]#
A signal to emit when a request is received.
- Returns:
- SignalInstance[RequestValue]
The signal instance related to a received request.
- async reply(reply: Reply) None #
Sends a reply back to a parent process once finished.
- Parameters:
- replyReply
The reply to be sent back to the parent.
- request: RequestPipe[RequestValue, ReplyValue]#
- class Reply(value: ReplyValue, identity: int)#
Bases:
Generic
[ReplyValue
]A reply to be returned to a requester.
- Attributes:
- value: ReplyValue
The reply token.
- identity: int
The identity associated with the request to receive a reply later.
- value: ReplyValue#
- class Request(value: RequestValue, identity: int)#
Bases:
Generic
[RequestValue
]A request to be sent to a replier.
- value: RequestValue
The request token.
- identity: int
The identity associated with the request to receive a reply later.
- classmethod generate(value: RequestValue)#
Generates a request with a unique identity.
- Parameters:
- valueRequestValue
The request token.
- Returns:
- Self
A request object for the request token provided.
- value: RequestValue#
- class RequestPipe(parent_send_to_child_pipe: _ConnectionBase, parent_recv_from_child_pipe: _ConnectionBase, child_send_to_parent_pipe: _ConnectionBase, child_recv_from_parent_pipe: _ConnectionBase)#
Bases:
Generic
[RequestValue
,ReplyValue
]A network of pipes to transmit requests and replies between two processes without causing conflicts.
..mermaid:
sequenceDiagram participant Parent participant Child Parent->>+Child: Request Status Child-->>-Parent: Return Status end
- Attributes:
- parent_send_to_child_pipe: Connection
A connection for a parent to send messages to a child process.
- parent_recv_from_child_pipe: Connection
A connection for a parent to receive messages for a child process.
- child_send_to_parent_pipe: Connection
A connection for a child to send messages to a parent process.
- child_recv_from_parent_pipe: Connection
A connection for a child to receive messages for a parent process.
- child_recv_from_parent_pipe: _ConnectionBase#
- child_send_to_parent_pipe: _ConnectionBase#
- classmethod generate()#
Generates a request pipe with a series of connections.
- Returns:
- Self
A new simple request pipe.
- parent_recv_from_child_pipe: _ConnectionBase#
- parent_send_to_child_pipe: _ConnectionBase#
- class Requester(request: RequestPipe[RequestValue, ReplyValue])#
Bases:
Generic
[RequestValue
,ReplyValue
]An abstraction of a parent process to facilitate requesting information between its children.
- Attributes:
- request: RequestPipe[RequestValue, ReplyValue]
An object to transmit data between processes.
- async check_received(identity: int) Optional[ReplyValue] #
Check if a reply has been received for a given request.
- Parameters:
- identityint
The identity of the request provided to the child.
- Returns:
- ReplyValue | None
The reply value if the child had replied, otherwise None.
- async get_answer(request: RequestValue) ReplyValue #
Sends a request and waits for a reply.
- Parameters:
- requestRequestValue
The request token.
- Returns:
- ReplyValue
The reply value.
- async receive_answer(identity: int) ReplyValue #
Ensures that an reply has been received from a child process.
- Parameters:
- identityint
The identity of the request to be replied to.
- Returns:
- ReplyValue
The reply value.
- request: RequestPipe[RequestValue, ReplyValue]#
- class Requests(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
Bases:
Enum
The types of requests that can be sent between a requester and receiver.
- Attributes:
- NOT_DEFINED
A request which is not defined. This should only be sent to denote an exception.
- GET_STATUS
A request to receive the status of the receiver.
- START_SLEEPING
A request for the receiver to enter sleep mode.
- STOP_SLEEPING
A request for the receiver to exit sleep mode.
- STOP
A request for the receiver to stop working and terminate.
- JOIN
A request for the receiver to finish all tasks currently active.
- LIMIT
A request for the receiver to not start tasks.
- GET_STATUS = 0#
- JOIN = 4#
- LIMIT = 5#
- NOT_DEFINED = -1#
- START_SLEEPING = 1#
- STOP = 3#
- STOP_SLEEPING = 2#
- SLOW_CONNECTION_POLLING_RATE: float = 0.001#
The desired rate of polling for a process that only requires periodic updates from the parent.
- class Status(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)#
Bases:
Enum
The possible states a receiver may possess.
..mermaid:
stateDiagram-v2 [*] --> STARTUP STARTUP --> RUNNING RUNNING --> RUNNING RUNNING --> SLEEPING : START SLEEPING SLEEPING --> RUNNING : STOP SLEEPING SLEEPING --> SLEEPING RUNNING --> STOPPED : STOP SLEEPING --> STOPPED : STOP STOPPED --> ZOMBIE ZOMBIE --> [*] end
- Attributes:
- NOT_DEFINED
A status which is not defined. This should only be sent to denote an exception.
- STARTUP
A status which denotes that the receiver is still initializing.
- RUNNING
A status which denotes that the receiver is actively receiving.
- SLEEPING
A status which denotes that the receiver is not receiving.
- STOPPED
A status which denotes that the receiver is no longer working.
- ZOMBIE
A status which denotes that the receiver only exists in presence and should be deleted promptly.
- SUCCESS
A status which generically denotes that the operation was successful.
- FAILURE
A status which generically denotes that the operation was not successful.
- FAILURE = 6#
- NOT_DEFINED = -1#
- RUNNING = 1#
- SLEEPING = 2#
- STARTUP = 0#
- STOPPED = 3#
- SUCCESS = 5#
- ZOMBIE = 4#
- class Task(task: Callable[[_P], _T], identity: int, required_tasks: Sequence[int] = [])#
Bases:
Generic
[_P
,_T
]A task to be paralyzed.
- Attributes:
- task: Callable[_P, _T]
The task that contains the complex computation which requires paralyzation.
- identity: int
The identity of the task.
- required_tasks: Sequence[int] = []
Tasks which are required to be complete prior to execution of this task.
- class TaskCallback(start_task: Callable[[_P], _T], return_task: Callable[[_T], None], exception_handler: collections.abc.Callable[[Exception], None] | None = None)#
Bases:
Generic
[_P
,_T
]A task which will execute additional information after the result of a task is complete.
..mermaid:
graph TD subgraph Main Process A[Task Callback] P[Manager Proxy] D --> P E --> P end subgraph Manager Process B[Task] A -->|schedule task| B end subgraph Worker Process C{Worker Task} C -.->|Success| D[Result] C -.->|Failure| E[Exception] end A --> P P --> A B --> C end
- Attributes:
- start_task: Callable[_P, _T]
The task to be paralyzed.
- return_task: Callable[[_T], None]
A function that will receive the result of the task.
- exception_handler: Callable[[Exception], None] | None = None
A handler that resolves exceptions inside the task provided.
- exception_handler: collections.abc.Callable[[Exception], None] | None#
- class TaskManager(name: str, outgoing_pipe: _ConnectionBase, incoming_pipe: _ConnectionBase, replier: Replier)#
Bases:
object
An abstraction of a process responsible for delegating tasks to a network of processes.
- Attributes:
- name: str
The name of the underlying process.
- outgoing_pipe: Connection
A pipe to send finished tasks to the parent process.
- incoming_pipe: Connection
A pipe to receive tasks from the parent process.
- replier: Replier
A network of pipes to easily reply to simple status requests from the parent process.
- recent_returned_values: dict[int, Any]
A mapping of finished tasks identities and their associated values.
- queued_tasks: dict[int, Task]
A mapping of tasks identities and their associated task that have not started.
- workers: list[TaskWorkerProxy]
A series of workers that can perform tasks.
- status: Status
The current status of the manager processes.
- last_event: float
The last time stamp that an event was sent to the task manager.
- async check_time() None #
Checks if the task manager is not actively being used. If the task manager is not being used, it will end itself.
- async default(identity: int) None #
Handles invalid requests by forwarding an invalid status to the main process.
- Parameters:
- identityint
The identity associated with the reply.
- async get_arguments_of_task(identity: int) list[Any] #
Acquires the arguments for a task which depends on other tasks.
- Parameters:
- identityint
The identity of the task to generate arguments for.
- Returns:
- list[Any]
The list of arguments for the task.
Notes
We assume that every return value exists.
- async get_important_return_values() set[int] #
Acquires all return value identities that are required for queued tasks.
- Returns:
- set[int]
The set of all return value identities that should not be removed.
- async get_status(identity: int) None #
Provides the status of the manager process to the main process.
- Parameters:
- identityint
The identity associated with the reply.
- handle_request(request: Request[Requests]) None #
Determines how to handle a simple request from the main process.
- Parameters:
- requestRequest[Requests]
The request token.
- incoming_pipe: _ConnectionBase#
- async join(identity: int) None #
Tries to finish all active tasks and enters sleeping mode.
- Parameters:
- identityint
The identity associated with the reply.
- async limit(identity: int) None #
A temporary effect used to ensure that tasks won’t finish until all tasks are provided.
- Parameters:
- identityint
The identity associated with the reply.
begun limiting tasks, otherwise a failure.
- outgoing_pipe: _ConnectionBase#
- async poll_queued_tasks(identity: int, return_value: Any) None #
Checks if any tasks that are queued are able to be started.
- Parameters:
- identityint
The identity of an additional task completed.
- return_valueAny
The return value of the additional task completed.
Notes
This should be called after each task is completed, so its data can be added and referenced later.
- async poll_workers() None #
Checks every worker to determine if any tasks have been completed and performs the required operations to send any finished tasks back to the main process.
- queued_tasks: dict[int, foundry.core.tasks.Task]#
- async remove_stale_return_values() None #
Removes return values that are no longer required by any queued task.
- async send_task_to_worker(task: Task, *args: Any) None #
Sends a task to one of the workers to be performed.
- Parameters:
- taskTask
The task to be sent and completed.
- async start_sleeping(identity: int) None #
Tries to put the manager process into sleep mode, refusing to receive additional tasks.
- Parameters:
- identityint
The identity associated with the reply.
- async stop(identity: int) None #
Stops the activity of the manager process.
- Parameters:
- identityint
The identity associated with the reply.
- async stop_sleeping(identity: int) None #
Tries to put the manager process into the running mode to undergo normal operation.
- Parameters:
- identityint
The identity associated with the reply.
- workers: list[foundry.core.tasks.TaskWorkerProxy]#
- class TaskManagerProxy(process: multiprocessing.context.Process | None, outgoing_pipe: _ConnectionBase, incoming_pipe: _ConnectionBase, requester: Requester[Requests, Status], name: str = 'manager')#
Bases:
object
An abstraction of a task manager to be ran on the main process to provide synchronized commands.
The task manager proxy servers as an interface to a multiple-staged process for distributing and paralyzing tasks in a continuous fashion. The model is as follows.
..mermaid:
graph TD B -.- D subgraph Main Process B(Task Manager Proxy) end subgraph Manager Process D[Task Manager]; D --- E; D --- F; D --- G E[Task Worker Proxy]; F[Task Worker Proxy]; G[Task Worker Proxy] end subgraph Worker Process direction LR E -.- H; H[Task Worker] end subgraph Worker Process direction LR I[Task Worker]; F -.- I end subgraph Worker Process direction LR J[Task Worker]; G -.- J end end
- process: Process | None
The process which contains the asynchronous task manager.
- outgoing_pipe: Connection
A pipe to send tasks to worker processes.
- incoming_pipe: Connection
A pipe to receive tasks from worker processes.
- requester: Requester[Requests, Status]
A requester object to receive simple commands to workers.
- name: str = “manager”
The name of the task manager, used for debugging.
- check_if_child_task_finished(task: TaskCallback, internal_task: Task) Callable[[FinishedTask], None] #
Checks if a task is finished from a receiver and performs the appropriate action depending if the task successfully completely.
- Parameters:
- taskTaskCallback
The task callback.
- internal_taskTask
The task containing its unique identity.
- Returns:
- Callable[[FinishedTask], None]
A function to perform the required actions for the task provided.
- incoming_pipe: _ConnectionBase#
- is_alive() bool #
Determines if the manager process is alive and exists.
- Returns:
- bool
If the manager process is alive.
- join(timeout: float | None = None) bool #
Stops the task manager from receiving additional tasks and waits for all pending tasks to complete.
- Parameters:
- timeoutfloat | None, optional
The amount of time permitted to wait until pending tasks are canceled, by default infinite.
- Returns:
- bool
If all tasks finished in the alloted amount of time.
- kill() None #
Abruptly kills and stops operation of the manager process quickly, likely leaving pending tasks in an indeterminate state.
- make_request(request: Requests, timeout: float | None = None) Status #
Makes a request to the task manager to change its operational status.
- Parameters:
- requestRequests
The request token.
- timeoutfloat | None, optional
The amount of time the program will wait for the task manager to respond, by default None or infinite.
- Returns:
- Status
The new state the task manager process has entered.
- outgoing_pipe: _ConnectionBase#
- poll_tasks() int #
Gets all the newly finished tasks and handles them.
- Returns:
- int
The amount of tasks completed.
- schedule_task(task: TaskCallback) None #
Schedules a single task.
- Parameters:
- taskTaskCallback
The task to be scheduled.
- schedule_tasks(tasks: Mapping[str, tuple[foundry.core.tasks.TaskCallback, set[str]]]) None #
Schedules a series of tasks.
- Parameters:
- tasksMapping[str, tuple[TaskCallback, set[str]]]
A mapping of a task name, task, and a set of required tasks.
Notes
Only the tasks and their associated identities inside tasks are ensured to exist.
- start(outgoing_pipe: _ConnectionBase, incoming_pipe: _ConnectionBase, replier: Replier) None #
Begins running the task manager in another process.
- Parameters:
- outgoing_pipeConnection
The pipe for the task manager process to send results to this process.
- incoming_pipeConnection
The pipe for the task manager process to receive tasks from this process.
- replierReplier
A network of pipes to receive simple requests from the parent process.
- property task_finished: SignalInstance#
A signal that is emitted when a task finishes.
- Returns:
- SignalInstance
The signal instance associated with finished tasks.
- class TaskMethod(fstart: Callable[[_P], _T], freturn: collections.abc.Callable[[Any, foundry.core.tasks._T], None] | None = None, fsignal: Optional[Signal[_T]] = None, ehandler: collections.abc.Callable[[Exception], None] | None = None, name: str | None = None)#
Bases:
Generic
[_P
,_T
]A method which will be executed and paralyzed.
- Attributes:
- name: str | None
The name associated with the method, by default will use the name of fstart
- fstart: Callable[_P, _T]
The task to be executed in another process.
- _freturn: Callable[[_T], None] | None
A method to handle the result of task.
- fsignal: Signal[_T] | None
A signal to emit the result of fstart.
- ehandler: Callable[[Exception], None] | None
A handler to resolve any exceptions from the task.
- ehandler: collections.abc.Callable[[Exception], None] | None#
- freturn(instance: object) Callable[[_T], None] #
A wrapped return function to enabled the use of a signal for successful completion of the task.
- Parameters:
- instanceobject
The instance of the method.
- Returns:
- Callable[[_T], None]
The wrapped return function.
- handler(ehandler: collections.abc.Callable | None = None)#
- return_task(freturn: collections.abc.Callable[[Any, foundry.core.tasks._T], None] | None)#
- task_callback(instance: object) TaskCallback[_P, _T] #
- class TaskWorker(name: str, outgoing_pipe: _ConnectionBase, incoming_pipe: _ConnectionBase, replier: Replier)#
Bases:
object
An abstraction of a worker process which is assigned a series of tasks to perform.
- Attributes:
- name: str
The name of the underlying process.
- outgoing_pipe: Connection
A pipe to send finished tasks to the manager process.
- incoming_pipe: Connection
A pipe to receive tasks from the manager process.
- replier: Replier
A network of pipes to easily reply to simple status requests from the manager process.
- status: Status
The current status of the worker processes.
- task_count: int
The number of tasks that this process is actively working on.
- async default(identity: int) None #
Handles invalid requests by forwarding an invalid status to the manager process.
- Parameters:
- identityint
The identity associated with the reply.
- async execute_task(task: WorkerTask) None #
Begins actively working on a task.
- Parameters:
- taskWorkerTask
The task to be performed.
- async get_status(identity: int) None #
Provides the status of the worker process to the manager process.
- Parameters:
- identityint
The identity associated with the reply.
- handle_request(request: Request[Requests]) None #
Determines how to handle a simple request from the main process.
- Parameters:
- requestRequest[Requests]
The request token.
- incoming_pipe: _ConnectionBase#
- async join(identity: int) None #
Tries to finish all active tasks and enters sleeping mode.
- Parameters:
- identityint
The identity associated with the reply.
- outgoing_pipe: _ConnectionBase#
- async start_sleeping(identity: int) None #
Tries to put the worker process into sleep mode, refusing to receive additional tasks.
- Parameters:
- identityint
The identity associated with the reply.
- async stop(identity: int) None #
Stops the activity of the worker process.
- Parameters:
- identityint
The identity associated with the reply.
- class TaskWorkerProxy(process: multiprocessing.context.Process | None, outgoing_pipe: _ConnectionBase, incoming_pipe: _ConnectionBase, requester: Requester[Requests, Status], name: str = 'worker')#
Bases:
object
An interface for the task manager to communicate to a worker process.
- Attributes:
- process: Process | None
The process which contains the asynchronous task manager.
- outgoing_pipe: Connection
A pipe to send tasks to worker processes.
- incoming_pipe: Connection
A pipe to receive tasks from worker processes.
- requester: Requester[Requests, Status]
A requester object to receive simple commands.
- name: str = “worker”
The name of the worker, used for debugging.
- incoming_pipe: _ConnectionBase#
- async is_alive() bool #
Determines if the worker process is alive and exists.
- Returns:
- bool
If the worker process is alive.
- async join(timeout: float | None = None) bool #
Stops the worker from receiving additional tasks and waits for all pending tasks to complete.
- Parameters:
- timeoutint | None, optional
The amount of time permitted to wait until pending tasks are canceled, by default infinite.
- Returns:
- bool
If all tasks finished in the alloted amount of time.
- async kill() None #
Abruptly kills and stops operation of the worker process quickly, likely not finishing all tasks.
- async make_request(request: Requests, timeout: float | None = None) Status #
Makes a request to the worker to change its operational status.
- Parameters:
- requestRequests
The request token.
- timeoutfloat | None, optional
The amount of time the program will wait for the task manager to respond, by default None or infinite.
- Returns:
- Status
The new state the worker process has entered.
- outgoing_pipe: _ConnectionBase#
- start(outgoing_pipe: _ConnectionBase, incoming_pipe: _ConnectionBase, replier: Replier) None #
Begins running the worker in another process.
- Parameters:
- outgoing_pipeConnection
The pipe for the worker process to send results to this process.
- incoming_pipeConnection
The pipe for the worker process to receive tasks from this process.
- replierReplier
A network of pipes to receive simple requests from the task manager.
- WORKER_SLEEP_DURATION: float = 0.001#
The desired rate of polling for a worker process of the task manager.
- class WorkerTask(task: Task[_P, _T], arguments: Sequence[Any] = [])#
Bases:
Generic
[_P
,_T
]A task to be sent to a worker.
- Attributes:
- task: Task[_P, _T]
The task to be ran by the worker.
- arguments: Sequence[Any] = []
The arguments of the task provided.
- begin_task() _T #
Begins execution of the task.
- Returns:
- _T
The result of the task.
- classmethod from_task(task: ~foundry.core.tasks.Task[~_P, ~foundry.core.tasks._T], *args: ~typing.~_P, **kwargs: ~typing.~_P)#
Generates a worker task from a task and a set of arguments.
- Parameters:
- taskTask[_P, _T]
The task to be wrapped.
- Returns:
- Self
A worker task specified by task.
- dill_connection(con1: _ConnectionBase, con2: _ConnectionBase) tuple[foundry.core.tasks.DilledConnection, foundry.core.tasks.DilledConnection] #
- exit_after(func: None = None, timeout: float | None = None) Callable[[Callable[[_P], _T]], Callable[[_P], Optional[_T]]] #
- exit_after(func: Callable[[_P], _T], timeout: float | None = None) Callable[[_P], Optional[_T]]
A decorator for a function to allow it to gracefully timeout and exit after a given period of time.
- Parameters:
- funcCallable[_P, _T] | None, optional
The function to be wrapped, by default None.
- timeoutfloat | None, optional
The amount of time until the function will time out, by default None or infinite.
- Returns:
- Callable[[Callable[_P, _T]], Callable[_P, _T]] | Callable[_P, _T]
If func is provided, the decorated function will be returned. Otherwise, a decorator will be provided.
- stage_task(instance: object, tasks: Mapping[str, tuple[foundry.core.tasks.TaskMethod, set[str]]]) None #
Allows for the staging of multiple task method to be ran in parallel.
- Parameters:
- instanceobject
The instance staging tasks.
- tasksMapping[str, tuple[TaskMethod, set[str]]]
A mapping of a task name, task, and a set of required tasks.
- start_task_manager(name: str | None = None) TaskManagerProxy #
Provides and starts a task manager to begin receiving and executing tasks.
- Parameters:
- namestr | None, optional
The name of the task manager process.
- Returns:
- TaskManagerProxy
An interface to communicate to the task manager process.
- synchronize(func)#
Allows for an asynchronous coroutine to be executed in the main process.
- Parameters:
- func
A coroutine to be executed in the main process.
- task#
alias of
TaskMethod
foundry.core.validators module#
- range_validator(minimum: int | None = None, maximum: int | None = None) Callable[[Any, Any, int], int] #
A validator for an ~`attrs.attrs` dataclass that ensures an int is between a minimum and maximum value.
- Parameters:
- minimumOptional[int]
The minimum value that the value is permitted to be. If minimum is None, then there will be no bound for the minimum value. By default, None.
- maximumOptional[int]
The maximum value that the value is permitted to be. If maximum is None, then there will be no bound for the maximum value. By default, None.
- Returns:
- Callable[[Any, Any, int], int]
A callable that acts as the true validator with a predefined minimum and maximum value.
Module contents#
- class ChainMap(*maps: Mapping)#
Bases:
Mapping
A ChainMap groups multiple dicts (or other mappings) together to create a single, updatable view.
Notes
Lookups search the underlying mappings successively until a key is found.
This is derived from the original collections ChainMap, but abbreviated to use attrs and be frozen.
- Attributes:
- The underlying mappings are stored in a tuple. That tuple is public and can
- be accessed or updated using the *maps* attribute. There is no other
- state.
- classmethod fromkeys(iterable, *args)#
Create a ChainMap with a single dict created from the iterable.
- get(k[, d]) D[k] if k in D, else d. d defaults to None. #
- maps: tuple[collections.abc.Mapping]#
- new_child(m: dict | None = None, **kwargs)#
New ChainMap with a new map followed by all previous maps.
Notes
If no map is provided, this instance will be returned.
- property parents#
New ChainMap from maps[1:].
- class ChainMapView(mapping: Mapping, *keys: Any, valid_keys: set | None = None)#
Bases:
Mapping
A view of a chain map, used to limit the values able to be acquired.
- Attributes:
- chain_map: ChainMap | ChainMapView
The underlying chain map to hide keys of.
- keys: Any
The keys of the set, if valid_keys is not set.
- valid_keys: set | None
The set of a valid keys. If None and there are no keys, it is assumed that all keys are valid.
- chain_map: foundry.core.ChainMap | foundry.core.ChainMapView#
- copy()#
- classmethod fromkeys(iterable, *args)#
Create a ChainMap with a single dict created from the iterable.
- get(k[, d]) D[k] if k in D, else d. d defaults to None. #
- property maps: tuple[collections.abc.Mapping]#
The maps associated with the underlying chain map.
- Returns:
- tuple[Mapping]
A series of maps that are present in the underlying chain map.
Notes
Does not hide invalid keys, defined from valid_keys.
- new_child(m=None, **kwargs)#
New ChainMap with a new map followed by all previous maps.
Notes
If no map is provided, an empty dict is used. Keyword arguments update the map or new empty dict.
- property parents#
New ChainMap from maps[1:].