flexmeasures.utils.coding_utils

Various coding utils (e.g. around function decoration)

Functions

flexmeasures.utils.coding_utils.deprecated(alternative, version: str | None = None)

Decorator for printing a warning error. alternative: importable object to use as an alternative to the function/method decorated version: version in which the function will be sunset

flexmeasures.utils.coding_utils.find_classes_module(module, superclass)
flexmeasures.utils.coding_utils.find_classes_modules(module, superclass, skiptest=True)
flexmeasures.utils.coding_utils.flatten_unique(nested_list_of_objects: list) list

Returns unique objects in a possibly nested (one level) list of objects.

For example: >>> flatten_unique([1, [2, 3, 4], 3, 5]) <<< [1, 2, 3, 4, 5]

flexmeasures.utils.coding_utils.get_classes_module(module, superclass, skiptest=True) dict
flexmeasures.utils.coding_utils.make_registering_decorator(foreign_decorator)

Returns a copy of foreign_decorator, which is identical in every way(*), except also appends a .decorator property to the callable it spits out.

# (*)We can be somewhat “hygienic”, but new_decorator still isn’t signature-preserving, i.e. you will not be able to get a runtime list of parameters. For that, you need hackish libraries… but in this case, the only argument is func, so it’s not a big issue

Works on outermost decorators, based on Method 3 of https://stackoverflow.com/a/5910893/13775459

flexmeasures.utils.coding_utils.methods_with_decorator(cls, decorator)

Returns all methods in CLS with DECORATOR as the outermost decorator.

DECORATOR must be a “registering decorator”; one can make any decorator “registering” via the make_registering_decorator function.

Doesn’t work for the @property decorator, but does work for the @functools.cached_property decorator.

Works on outermost decorators, based on Method 3 of https://stackoverflow.com/a/5910893/13775459

flexmeasures.utils.coding_utils.optional_arg_decorator(fn)

A decorator which _optionally_ accepts arguments.

So a decorator like this:

@optional_arg_decorator def register_something(fn, optional_arg = ‘Default Value’):

… return fn

will work in both of these usage scenarios:

@register_something(‘Custom Name’) def custom_name():

pass

@register_something def default_name():

pass

Thanks to https://stackoverflow.com/questions/3888158/making-decorators-with-optional-arguments#comment65959042_24617244

flexmeasures.utils.coding_utils.rgetattr(obj, attr, *args)

Get chained properties.

Usage

>>> class Pet:
        def __init__(self):
            self.favorite_color = "orange"
>>> class Person:
        def __init__(self):
            self.pet = Pet()
>>> p = Person()
>>> rgetattr(p, 'pet.favorite_color')  # "orange"

From https://stackoverflow.com/a/31174427/13775459

flexmeasures.utils.coding_utils.sort_dict(unsorted_dict: dict) dict
flexmeasures.utils.coding_utils.timeit(func)

Decorator for printing the time it took to execute the decorated function.