pak.dyn_value

Code for transforming certain values into dynamic values.

class DynamicValue(initial_value)[source]

Bases: ABC

A definition of how to dynamically get one value from another.

Types and Packets have certain attributes whose values can be transformed into something callable-ish. DynamicValue is the mechanism behind that transformation.

To enroll a certain type into the DynamicValue machinery, make a subclass of DynamicValue, setting the _type attribute to the type in question. Doing so will “enable” the subclass on class initialization. This can be overridden by setting the _enabled attribute explicitly.

Alternatively, there are also the enable() and disable() methods, and the context() method for context management.

For instance, to enroll str into 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_value is something for DynamicValue to deal with, then an instance of the appropriate subclass will be returned.

Otherwise, initial_value is returned.

Return type:

any

_type

The type for the DynamicValue to deal with.

Type:

type

_enabled

Whether the DynamicValue is enabled.

Type:

bool

classmethod enable()[source]

Enables the class to be used in the DynamicValue machinery.

classmethod disable()[source]

Disables the class to be used in the DynamicValue machinery.

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.Context or Type.Context) – The context for the dynamic value.

Returns:

The dynamic value.

Return type:

any