pak.dyn_value¶
Code for transforming certain values into dynamic values.
- class DynamicValue(initial_value)[source]¶
Bases:
ABCA definition of how to dynamically get one value from another.
Types andPackets have certain attributes whose values can be transformed into something callable-ish.DynamicValueis the mechanism behind that transformation.To enroll a certain type into the
DynamicValuemachinery, make a subclass ofDynamicValue, setting the_typeattribute to the type in question. Doing so will “enable” the subclass on class initialization. This can be overridden by setting the_enabledattribute explicitly.Alternatively, there are also the
enable()anddisable()methods, and thecontext()method for context management.For instance, to enroll
strinto the machinery:import pak class StringDynamicValue(pak.DynamicValue): _type = str # The initial value is passed to # the constructor. def __init__(self, string): self.string = string # The dynamic value is returned # from the "get" method. # # Here we return the reversed string. def get(self, *, ctx=None): return self.string[::-1] # This will lead to the following behavior: v = pak.DynamicValue("Hello") print(isinstance(v, StringDynamicValue)) print(v.get()) StringDynamicValue.disable() print(pak.DynamicValue("Hello"))
True olleH Hello
- Parameters:
initial_value – The initial value for the
DynamicValue.- Returns:
If the type of
inital_valueis something forDynamicValueto deal with, then an instance of the appropriate subclass will be returned.Otherwise,
initial_valueis returned.- Return type:
any
- _type¶
The type for the
DynamicValueto deal with.- Type:
type
- _enabled¶
Whether the
DynamicValueis enabled.- Type:
bool
- classmethod enable()[source]¶
Enables the class to be used in the
DynamicValuemachinery.
- classmethod disable()[source]¶
Disables the class to be used in the
DynamicValuemachinery.
- classmethod context()[source]¶
Temporarily enables then disables the class.
Examples
>>> import pak >>> class StringToIntDynamicValue(pak.DynamicValue): ... _type = str ... def __init__(self, string): ... self.string = string ... def get(self, *, ctx=None): ... return int(self.string) ... >>> with StringToIntDynamicValue.context(): ... print(isinstance(pak.DynamicValue("1"), StringToIntDynamicValue)) ... True >>> pak.DynamicValue("1") '1'
- abstract get(*, ctx=None)[source]¶
Gets the dynamic value.
- Parameters:
ctx (
Packet.ContextorType.Context) – The context for the dynamic value.- Returns:
The dynamic value.
- Return type:
any