跳转至

Utilities

chanfig.to_dict

Convert an object to a dict.

Note that when converting a set object, it may be converted to a tuple object if its values is not hashable.

Parameters:

Name Type Description Default
obj Any

Object to be converted.

required

Returns:

Type Description
Mapping[str, Any]

A dict.

Examples:

Python Console Session
>>> to_dict(1)
1
>>> to_dict([1, 2, 3])
[1, 2, 3]
>>> to_dict((1, 2, 3))
(1, 2, 3)
>>> to_dict({1, 2, 3})
{1, 2, 3}
>>> to_dict({'a': 1, 'b': 2})
{'a': 1, 'b': 2}
>>> to_dict(Variable(1))
1
>>> to_dict(FlatDict(a=[[[[[FlatDict(b=1)]]]]]))
{'a': [[[[[{'b': 1}]]]]]}
>>> to_dict(FlatDict(a={FlatDict(b=1)}))
{'a': ({'b': 1},)}
Source code in chanfig/flat_dict.py
Python
def to_dict(obj: Any) -> Mapping[str, Any]:  # pylint: disable=R0911
    r"""
    Convert an object to a dict.

    Note that when converting a `set` object, it may be converted to a `tuple` object if its values is not hashable.

    Args:
        obj: Object to be converted.

    Returns:
        A dict.

    Examples:
        >>> to_dict(1)
        1
        >>> to_dict([1, 2, 3])
        [1, 2, 3]
        >>> to_dict((1, 2, 3))
        (1, 2, 3)
        >>> to_dict({1, 2, 3})
        {1, 2, 3}
        >>> to_dict({'a': 1, 'b': 2})
        {'a': 1, 'b': 2}
        >>> to_dict(Variable(1))
        1
        >>> to_dict(FlatDict(a=[[[[[FlatDict(b=1)]]]]]))
        {'a': [[[[[{'b': 1}]]]]]}
        >>> to_dict(FlatDict(a={FlatDict(b=1)}))
        {'a': ({'b': 1},)}
    """

    if isinstance(obj, Mapping):
        return {k: to_dict(v) for k, v in obj.items()}
    if isinstance(obj, list):
        return [to_dict(v) for v in obj]  # type: ignore
    if isinstance(obj, tuple):
        return tuple(to_dict(v) for v in obj)  # type: ignore
    if isinstance(obj, set):
        try:
            return set(to_dict(v) for v in obj)  # type: ignore
        except TypeError:
            return tuple(to_dict(v) for v in obj)  # type: ignore
    if isinstance(obj, Variable):
        return obj.value
    return obj

chanfig.utils.apply

Apply func to all children of obj.

Note that this function is meant for non-in-place modification of obj and should return the original object.

Parameters:

Name Type Description Default
obj Any

Object to apply function.

required
func Callable

Function to be applied.

required
*args

Positional arguments to be passed to func.

()
**kwargs

Keyword arguments to be passed to func.

{}

Returns:

Type Description
Any

Return value of func.

See Also

apply_: Apply a in-place operation.

Source code in chanfig/utils.py
Python
def apply(obj: Any, func: Callable, *args, **kwargs) -> Any:
    r"""
    Apply `func` to all children of `obj`.

    Note that this function is meant for non-in-place modification of `obj` and should return the original object.

    Args:
        obj: Object to apply function.
        func: Function to be applied.
        *args: Positional arguments to be passed to `func`.
        **kwargs: Keyword arguments to be passed to `func`.

    Returns:
        (Any): Return value of `func`.

    See Also:
        [`apply_`][chanfig.utils.apply_]: Apply a in-place operation.
    """

    if isinstance(obj, Mapping):
        return type(obj)({k: apply(v, func, *args, **kwargs) for k, v in obj.items()})  # type: ignore
    if isinstance(obj, (list, tuple)):
        return type(obj)(apply(v, func, *args, **kwargs) for v in obj)  # type: ignore
    if isinstance(obj, set):
        try:
            return type(obj)(apply(v, func, *args, **kwargs) for v in obj)  # type: ignore
        except TypeError:
            tuple(apply(v, func, *args, **kwargs) for v in obj)  # type: ignore
    return func(*args, **kwargs) if ismethod(func) else func(obj, *args, **kwargs)

chanfig.utils.apply_

Apply func to all children of obj.

Note that this function is meant for non-in-place modification of obj and should return a new object.

Parameters:

Name Type Description Default
obj Any

Object to apply function.

required
func Callable

Function to be applied.

required
*args

Positional arguments to be passed to func.

()
**kwargs

Keyword arguments to be passed to func.

{}

Returns:

Type Description
Any

Return value of func.

See Also

apply_: Apply a in-place operation.

Source code in chanfig/utils.py
Python
def apply_(obj: Any, func: Callable, *args, **kwargs) -> Any:
    r"""
    Apply `func` to all children of `obj`.

    Note that this function is meant for non-in-place modification of `obj` and should return a new object.

    Args:
        obj: Object to apply function.
        func: Function to be applied.
        *args: Positional arguments to be passed to `func`.
        **kwargs: Keyword arguments to be passed to `func`.

    Returns:
        (Any): Return value of `func`.

    See Also:
        [`apply_`][chanfig.utils.apply_]: Apply a in-place operation.
    """

    if isinstance(obj, Mapping):
        [apply_(v, func, *args, **kwargs) for v in obj.values()]  # type: ignore
    if isinstance(obj, (list, tuple, set)):
        [apply_(v, func, *args, **kwargs) for v in obj]  # type: ignore
    return func(*args, **kwargs) if ismethod(func) else func(obj, *args, **kwargs)

chanfig.utils.Singleton

Bases: type

Metaclass for Singleton Classes.

Source code in chanfig/utils.py
Python
class Singleton(type):
    r"""
    Metaclass for Singleton Classes.
    """

    __instances__: Mapping[type, object] = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls.__instances__:
            cls.__instances__[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls.__instances__[cls]

chanfig.utils.Null

Null is an instance of NULL.

Since the metaclass of NULL is Singleton, it is advised to use obj is Null to determine if obj is Null.

chanfig.utils.NULL

NULL class.

get method in CHANfiG may accept None or Ellipse(...) as value of default. Therefore, it is mandatory to have a different default value for default.

Null is an instance of NULL and is recommended to be used as obj is Null.

Source code in chanfig/utils.py
Python
class NULL(metaclass=Singleton):
    r"""
    NULL class.

    `get` method in CHANfiG may accept `None` or `Ellipse`(`...`) as value of `default`.
    Therefore, it is mandatory to have a different default value for `default`.

    `Null` is an instance of `NULL` and is recommended to be used as `obj is Null`.
    """

    def __repr__(self):
        return "Null"

    def __nonzero__(self):
        return False

    def __len__(self):
        return 0

    def __call__(self, *args, **kwargs):
        return self

    def __contains__(self, name):
        return False

    def __iter__(self):
        return self

    def __next__(self):
        raise StopIteration

    def __getattr__(self, name):
        return self

    def __getitem__(self, index):
        return self

chanfig.utils.JsonEncoder

Bases: JSONEncoder

JSON encoder for Config.

Source code in chanfig/utils.py
Python
class JsonEncoder(JSONEncoder):
    r"""
    JSON encoder for Config.
    """

    def default(self, o: Any) -> Any:
        if isinstance(o, Variable):
            return o.value
        if hasattr(o, "__json__"):
            return o.__json__()
        return super().default(o)

chanfig.utils.YamlDumper

Bases: SafeDumper

YAML Dumper for Config.

Source code in chanfig/utils.py
Python
class YamlDumper(SafeDumper):  # pylint: disable=R0903
    r"""
    YAML Dumper for Config.
    """

    def increase_indent(self, flow: bool = False, indentless: bool = False):  # pylint: disable=W0235
        return super().increase_indent(flow, indentless)

chanfig.utils.YamlLoader

Bases: SafeLoader

YAML Loader for Config.

Source code in chanfig/utils.py
Python
class YamlLoader(SafeLoader):  # pylint: disable=R0901,R0903
    r"""
    YAML Loader for Config.
    """

最后更新: 2023-05-20 15:08:43