Function decorators

A variety of useful function decorators for logging and more.

Main features in this module:

Module author: Marc Claesen

class optunity.functions.Args(*args, **kwargs)[source]

Bases: object

Class to model arguments to a function evaluation. Objects of this class are hashable and can be used as dict keys.

Arguments and keyword arguments are stored in a frozenset.

keys()[source]

Returns a list of argument names.

parameters[source]

Returns the internal representation.

values()[source]

Returns a list of argument values.

class optunity.functions.CallLog[source]

Bases: object

Thread-safe call log.

The call log is an ordered dictionary containing all previous function calls. Its keys are dictionaries representing the arguments and its values are the function values. As dictionaries can’t be used as keys in dictionaries, a custom internal representation is used.

Initialize an empty CallLog.

data[source]

Access internal data after obtaining lock.

delete(*args, **kwargs)[source]
static from_dict(d)[source]

Converts given dict to a valid call log used by logged functions.

Given dictionary must have the following structure: {'args': {'argname': []}, 'values': []}

>>> log = CallLog.from_dict({'args': {'x': [1, 2]}, 'values': [2, 3]})
>>> print(log)
{'x': 1} --> 2
{'x': 2} --> 3
get(*args, **kwargs)[source]

Returns the result of given evaluation or None if not previously done.

insert(value, *args, **kwargs)[source]
items()[source]
keys()[source]
lock[source]
to_dict()[source]

Returns given call_log into a dictionary.

The result is a dict with the following structure: {'args': {'argname': []}, 'values': []}

>>> call_log = CallLog()
>>> call_log.insert(3, x=1, y=2)
>>> d = call_log.to_dict()
>>> d['args']['x']
[1]
>>> d['args']['y']
[2]
>>> d['values']
[3]
update(other)[source]
values()[source]
exception optunity.functions.MaximumEvaluationsException(max_evals)[source]

Bases: exceptions.Exception

Raised when the maximum number of function evaluations are used.

args
max_evals[source]

Returns the maximum number of evaluations that was permitted.

message
optunity.functions.logged(f)[source]

Decorator that logs unique calls to f.

The call log can always be retrieved using f.call_log. Decorating a function that is already being logged has no effect.

The call log is an instance of CallLog.

>>> @logged
... def f(x): return x+1
>>> a, b, c = f(1), f(1), f(2)
>>> print(f.call_log)
{'pos_0': 1} --> 2
{'pos_0': 2} --> 3

logged as inner decorator:

>>> from .constraints import constrained
>>> @logged
... @constrained([lambda x: x > 1])
... def f2(x): return x+1
>>> len(f2.call_log)
0
>>> f2(2)
3
>>> print(f2.call_log)
{'pos_0': 2} --> 3

logged as outer decorator:

>>> from .constraints import constrained
>>> @constrained([lambda x: x > 1])
... @logged
... def f3(x): return x+1
>>> len(f3.call_log)
0
>>> f3(2)
3
>>> print(f3.call_log)
{'pos_0': 2} --> 3
>>> @logged
... def f(x): return 1
>>> f(1)
1
>>> print(f.call_log)
{'pos_0': 1} --> 1
>>> @logged
... @functools.wraps(f)
... def f2(x): return f(x)
>>> print(f2.call_log)
{'pos_0': 1} --> 1
optunity.functions.max_evals(max_evals)[source]

Decorator to enforce a maximum number of function evaluations.

Throws a MaximumEvaluationsException during evaluations after the maximum is reached. Adds a field f.num_evals which tracks the number of evaluations that have been performed.

>>> @max_evals(1)
... def f(x): return 2
>>> f(2)
2
>>> f(1) 
Traceback (most recent call last):
...
MaximumEvaluationsException
>>> try:
...    f(1)
... except MaximumEvaluationsException as e:
...    e.max_evals
1
Traceback (most recent call last):
...
MaximumEvaluationsException
optunity.functions.negated(f)[source]

Decorator to negate f such that f’(x) = -f(x).

optunity.functions.static_key_order(keys)[source]

Decorator to fix the key order for use in function evaluations.

A fixed key order allows the function to be evaluated with a list of unnamed arguments rather than kwargs.

>>> @static_key_order(['foo', 'bar'])
... def f(bar, foo): return bar + 2 * foo
>>> f(3, 5)
11

Table Of Contents

This Page

Previous topic

Domain constraints

Next topic

Standalone implementation