jacinle.utils.defaults#
Module attributes
|
A special value to indicate that the default value of an argument will be determined in a deferred manner. |
Classes
Defaults manager can be used to create program or thread-level registries. |
|
A class that stores options in a single file. |
Functions
|
A helper function handles the case of "fall-through" default arguments. |
|
|
|
|
Class DefaultsManager
- class DefaultsManager[source]#
Bases:
object
Defaults manager can be used to create program or thread-level registries. One of the typical use case is that you can create an instance of a specific class, and then set it as the default, and then get this instance from elsewhere.
For example:
>>> class Storage(object): ... def __init__(self, value): ... self.value = value >>> storage = Storage(1) >>> set_defualt_storage(storage) >>> get_default_storage() # now you can call this elsewhere.
Another important feature supported by this default manager is that it allows you to have “nested” default registries.
For example:
>>> get_default_storage().value # -> 1 >>> with Stoage(2).as_default(): ... get_default_storage().value # -> 2 ... with Storage(3).as_default(): ... get_default_storage().value # -> 3 ... get_default_storage().value # -> 2
Similar features have been used commonly in TensorFlow, e.g., tf.Session, tf.Graph.
To create a class with a default registry, use the following:
class Storage(object): def __init__(self, value): self.value = value @defaults_manager.wrap_custom_as_default(is_local=True) def as_default(self): # this is a contextmanager yield get_default_storage = defaults_manager.gen_get_default(Storage) set_default_storage = defaults_manager.gen_set_default(Storage)
- __new__(**kwargs)#
Class FileOptions
- class FileOptions[source]#
Bases:
object
A class that stores options in a single file.
Example
# file: my_module.py options = FileOptions(__file__, number_to_add=1) def my_func(x: int) -> int: return x + options.number_to_add # file: my_script.py import my_module my_module.options.set(number_to_add=2) my_module.my_func(1) # returns 3
- __new__(**kwargs)#
Functions
- default_args(func)[source]#
A helper function handles the case of “fall-through” default arguments. Suppose we have two functions:
f
andg
, andf
callsg
.g
has a default argumentx
, e.g.,x=1
. In many cases, we do not want to specify the default value ofx
inf
. One way to do this is to useNone
as the default value ofx
inf
, and then check ifx
isNone
ing
. However this does not handle cases wherex
can beNone
in other cases. It also requires additional checks ing
. With this decorator, we can simply writex=ARGDEF
inf
, and thenx
will be set to1
ing
.Example
def f(x=ARGDEF): g(x) @default_args def g(x=1): print(x) f() # prints 1 f(2) # prints 2
- gen_get_default()#
- gen_set_default(cls)#
- wrap_custom_as_default()#