Function

class audobject.resolver.Function[source]

Function resolver.

Encodes source code of function and dynamically evaluates it when the value is decoded again.

Note that a decoded function might raise a NameError, if it relies on objects or functions that are not defined or imported inside the function. For instance, the following example will raise an error since plus_1() relies on _plus_1(), which is defined outside the function:

def _plus_1(x):
    return x + 1

def plus_1(x):
    return _plus_1(x)  # calls local function -> not serializable

resolver = Function()
encoded_value = resolver.encode(plus_1)
del _plus_1
decoded_value = resolver.decode(encoded_value)
decoded_value(1)

Examples

>>> resolver = Function()
>>> def func(x):
...     return x * 2
>>> func(5)
10
>>> encoded_value = resolver.encode(func)
>>> encoded_value
'def func(x):\n    return x * 2\n'
>>> decoded_value = resolver.decode(encoded_value)
>>> decoded_value(5)
10

__hash__()

Function.__hash__()

Return hash(self).

decode()

Function.decode(value)[source]

Decode (lambda) function.

Parameters

value (str) – source code

Return type

Callable

Returns

function object

encode()

Function.encode(value)[source]

Encode (lambda) function.

Parameters

value (Callable) – function object

Return type

Union[str, object]

Returns

source code

encode_type()

Function.encode_type()[source]

Returns encoded type.

Return type

type

Returns

encoded type

get_source()

Function.get_source(func)[source]

Obtain source code of (lambda) function.

Retrieving the source of a lambda function can become tricky, see the following link for detailed discussion:

http://xion.io/post/code/python-get-lambda-code.html

Parameters

func (Callable) – function object

Return type

str

Returns

source code

root

Function.root

Root folder.

Returns root folder when object is serialized to or from a file, otherwise None is returned.

Returns

root directory