optmanage.manager

Base class for option managers.

OptionManager

class OptionManager[source]

Bases: object

A base class that can be used to implement flexible option managers, supporting options with default values, static type hints, runtime type checking, and custom runtime validation logic.

Subclasses should define options as class attributes, using the Option descriptor.

A simple example of an option manager:

class MyOptions(OptionManager):
    ''' Options of some library. '''

    validate = Option(bool, True)
    ''' Whether to validate arguments to  functions and methods. '''

    eq_atol = Option(float, 1e-08, lambda x: x >= 0)
    ''' Absolute tolerance used for equality comparisons.'''

    print_prec = Option(int, 3, lambda x: x >= 0)
    ''' Number of decimal digits to be displayed when printing. '''

Each option is defined as a class attribute of type Option, passing a default value, a type, and optionally a validator function:

validate = Option(bool, True)
#     option type ^^^^  ^^^^ default value

print_prec = Option(int, 3, lambda x: x >= 0)
#        optional validator ^^^^^^^^^^^^^^^^

The option manager can then be instantiated as usual:

options = MyOptions()
__call__(**option_values)[source]

With-context manager to temporarily set option values.

Example usage:

with options(print_prec=5):
    # Sets 'print_prec' to 5 temporarily in this context.
    ...
# Value of 'print_prec' is restored to its previous value here.
Parameters:

option_values (Any; variadic keyword) –

Return type:

Iterator[None]

__getitem__(name)[source]

Gets the value of the given option.

Parameters:

name (str) –

Return type:

Any

__setitem__(name, value)[source]

Sets the value of the given option.

For errors, see Option.__set__.

Parameters:
  • name (str) –

  • value (Any) –

Return type:

None

items()[source]

Iterator over option name-value pairs.

Return type:

Iterator[tuple[str, Any]]

keys()[source]

Iterator over option names.

Return type:

Iterator[str]

reset()[source]

Resets all options to their default values. Returns the old values for all options.

Example usage:

options.reset()
# Permanently resets all options to default values.

For errors, see Option.reset.

Return type:

Mapping[str, Any]

set(**option_values)[source]

Sets values for the given options. Returns the old values of the options that were set.

Example usage:

options.set(validate=False, print_prec=5)
# Permanently sets 'validate' and 'print_prec' options.

For errors, see Option.__set__.

Parameters:

option_values (Any; variadic keyword) –

Return type:

Mapping[str, Any]

values()[source]

Iterator over option values.

Return type:

Iterator[Any]