jacinle.utils.meta#

Module attributes

UNSET

A special object to indicate that a value is not set.

Classes

Clock

A clock that can be used to measure the time.

Functions

assert_instance(ins, clz[, msg])

Assert that an instance is of a certain type.

assert_none(ins[, msg])

Assert that the input is None.

assert_notnone(ins[, msg, name])

Assert that the input is not None.

cond_with(with_statement, cond)

A context manager that runs a with statement only if the condition is true.

cond_with_group(cond, *with_statement)

A context manager that runs a group of with statements only if the condition is true.

decorator_with_optional_args([func, is_method])

Make a decorator that can be used with or without arguments.

dict_deep_keys(d[, sort, sep, allow_dict])

Get the keys of a flattened dictionary.

dict_deep_kv(d[, sort, sep, allow_dict])

Get a flattened dictionary with keys as the path to the value.

dict_deep_update(a, b)

Update a dictionary recursively.

filter_exec(func, iterable)

Execute a filter function on each element of the iterable, and return the results.

first(iterable[, default])

Get the first element of an iterable.

first_n(iterable[, n])

Get the first n elements of an iterable.

gofor(v)

A go-style for loop for dict, list, tuple, set, etc.

make_dummy_func([message])

Make a dummy function that raises an error when called.

map_exec(func, *iterables)

Execute a function on each element of the iterables, and return the results.

map_exec_method(method_name, iterable)

Execute a method on each element of the iterable, and return the results.

merge_iterable(v1, v2)

Merge two iterables into a single iterable.

method2func(method_name)

Convert a method name to a function that calls the method.

notnone_property(fget)

A property that raises an error if the value is None.

repr_from_str(self)

A helper function to generate the repr string from the __str__ method.

run_once(func)

A decorator to run a function only once.

stmap(func, iterable)

A map function that recursively follows the structure of the iterable.

synchronized([mutex])

A decorator that synchronizes the execution of a function.

timeout(timeout[, fps])

A decorator that raises a TimeoutError if the execution time of the function exceeds the timeout.

try_run(lambda_)

A function that tries to run a function, and returns None if it fails (without raising exceptions).

Class Clock

class Clock[source]#

Bases: object

A clock that can be used to measure the time.

__init__(tick=None)[source]#

Initialize the clock.

Parameters:

tick (float | None) – the time (second) for each tick of the clock.

__new__(**kwargs)#
tick(timeout=None)[source]#

Tick the clock.

Parameters:

timeout – the timeout in seconds. If not specified, the timeout in the constructor will be used.

Functions

assert_instance(ins, clz, msg=None)[source]#

Assert that an instance is of a certain type.

Parameters:
assert_none(ins, msg=None)[source]#

Assert that the input is None.

Parameters:
assert_notnone(ins, msg=None, name=None)[source]#

Assert that the input is not None.

Parameters:
  • ins (Any) – the input.

  • msg (str) – the error message. If not specified, a default message {name} is None will be used.

  • name (str) – the name of the input.

cond_with(with_statement, cond)[source]#

A context manager that runs a with statement only if the condition is true.

Parameters:

cond (bool)

cond_with_group(cond, *with_statement)[source]#

A context manager that runs a group of with statements only if the condition is true.

Parameters:

cond (bool)

decorator_with_optional_args(func=None, *, is_method=False)[source]#

Make a decorator that can be used with or without arguments.

Parameters:
  • func – the function to be decorated.

  • is_method – whether the function is a method.

Example

 @decorator_with_optional_args
 def my_decorator(func=None, *, a=1, b=2):
     def wrapper(func):
         @functools.wraps(func)
         def new_func(*args, **kwargs):
             print(f'Calling {func.__name__} with a={a}, b={b}')
             return func(*args, **kwargs)
         return new_func
     return wrapper

 @my_decorator
 def func1():
     pass  # Calling func1 with a=1, b=2

 @my_decorator(a=2)
 def func2():
pass  # Calling func2 with a=2, b=2
dict_deep_keys(d, sort=True, sep='.', allow_dict=False)[source]#

Get the keys of a flattened dictionary.

Parameters:
  • d (Dict[Any, Any]) – the dictionary.

  • sort (bool) – whether to sort the keys.

  • sep – the separator between keys.

  • allow_dict (bool) – whether to allow dictionary values.

Returns:

a list of keys.

Return type:

List[str]

See also

dict_deep_kv()

dict_deep_kv(d, sort=True, sep='.', allow_dict=False)[source]#

Get a flattened dictionary with keys as the path to the value.

Example

>>> d = {'a': 1, 'b': {'c': 2, 'd': 3}}
>>> dict_deep_kv(d)
{'a': 1, 'b.c': 2, 'b.d': 3}
Parameters:
  • d (Dict[Any, Any]) – the dictionary.

  • sort (bool) – whether to sort the keys.

  • sep – the separator between keys.

  • allow_dict (bool) – whether to allow dictionary values.

Return type:

Dict[str, Any]

dict_deep_update(a, b)[source]#

Update a dictionary recursively.

Parameters:
  • a (Dict[Any, Any]) – the dictionary to be updated.

  • b (Dict[Any, Any]) – the dictionary to update from.

filter_exec(func, iterable)[source]#

Execute a filter function on each element of the iterable, and return the results.

Parameters:

iterable (Iterable[Any])

Return type:

List[Any]

first(iterable, default=None)[source]#

Get the first element of an iterable. If the iterable is empty, return the default value.

Parameters:
  • iterable (Iterable[Any]) – the iterable object.

  • default (Any) – the default value.

Returns:

the first element of the iterable, or the default value.

Return type:

Any

first_n(iterable, n=10)[source]#

Get the first n elements of an iterable. If the iterable has less than n elements, return None.

Parameters:
  • iterable (Iterable) – the iterable object.

  • n (int) – the number of elements to get.

Returns:

the first n elements of the iterable, or None.

Return type:

List[Any] | None

gofor(v)[source]#

A go-style for loop for dict, list, tuple, set, etc.

  • dict: for key, value in gofor(dict):

  • list, tuple, set: for index, value in gofor(list):

Parameters:

v (Iterable[Any]) – the iterable object.

Return type:

Iterable[Tuple[Any, Any]]

make_dummy_func(message=None)[source]#

Make a dummy function that raises an error when called.

map_exec(func, *iterables)[source]#

Execute a function on each element of the iterables, and return the results.

Parameters:

iterables (Iterable[Any])

Return type:

List[Any]

map_exec_method(method_name, iterable)[source]#

Execute a method on each element of the iterable, and return the results.

Parameters:
  • method_name – the method name.

  • iterable (Iterable[Any]) – the iterable object.

Return type:

List[Any]

merge_iterable(v1, v2)[source]#

Merge two iterables into a single iterable.

  • list, tuple: return v1 + v2

  • set: return v1 | v2

  • dict: return {**v1, **v2}

Parameters:
  • v1 – the first iterable.

  • v2 – the second iterable.

Returns:

the merged iterable.

method2func(method_name)[source]#

Convert a method name to a function that calls the method. Equivalent to lambda x: x.method_name().

Parameters:

method_name (str) – the method name.

Return type:

Callable

notnone_property(fget)[source]#

A property that raises an error if the value is None.

repr_from_str(self)[source]#

A helper function to generate the repr string from the __str__ method.

Example

class Foo(object):
    def __str__(self):
        return 'Foo'

    __repr__ = repr_from_str

print(Foo())  # Foo
print(repr(Foo()))  # Foo[Foo]
run_once(func)[source]#

A decorator to run a function only once.

stmap(func, iterable)[source]#

A map function that recursively follows the structure of the iterable.

  • list, tuple: return [func(v) for v in iterable]

  • set: return {func(v) for v in iterable}

  • dict: return {k: func(v) for k, v in iterable.items()}

Parameters:
  • func – the function to be applied.

  • iterable (Iterable[Any]) – the iterable object.

Returns:

the mapped iterable.

Return type:

Iterable[Any]

synchronized(mutex=None)[source]#

A decorator that synchronizes the execution of a function.

Parameters:

mutex – the mutex to use. If not specified, a new threading mutex will be created.

timeout(timeout, fps=None)[source]#

A decorator that raises a TimeoutError if the execution time of the function exceeds the timeout.

Parameters:
  • timeout (float) – timeout in seconds.

  • fps (float) – an optional fps to control the maximum number of iterations.

Example

import time
from jacinle.utils.meta import timeout
for _ in timeout(5.1):
    print('hello')
    time.sleep(1)
try_run(lambda_)[source]#

A function that tries to run a function, and returns None if it fails (without raising exceptions).