Utils

Constants

These constants are used throughout Yuio whenever None is too ambiguous.

yuio.DISABLED: Literal[_Placeholders.DISABLED] = yuio.DISABLED

Indicates that some functionality is disabled.

yuio.MISSING: Literal[_Placeholders.MISSING] = yuio.MISSING

Indicates that some value is missing.

yuio.POSITIONAL: Literal[_Placeholders.POSITIONAL] = yuio.POSITIONAL

Used with yuio.app.field() to enable positional arguments.

yuio.COLLAPSE: Literal[_Placeholders.COLLAPSE] = yuio.COLLAPSE

Used with yuio.app.field() to omit arguments from CLI usage and to collapse argument groups.

Errors and debugging

yuio.enable_internal_logging(
path: str | None = None,
level: str | int | None = None,
propagate=None,
add_handler: bool = False,
)

Enable Yuio’s internal logging.

This function enables logging.captureWarnings(), and enables printing of YuioWarning messages, and sets up logging channels yuio.internal and py.warning.

Parameters:
  • path – if given, adds handlers that output internal log messages to the given file.

  • level – configures logging level for file handler. Default is DEBUG.

  • propagate – if given, enables or disables log message propagation from yuio.internal and py.warning to the root logger.

  • add_handler – if True, adds yuio handler to the logging. This is useful if you wish to see yuio log before main setup.

class yuio.PrettyException(msg: LiteralString, /, *args: Any)
class yuio.PrettyException(msg: Template, /)
class yuio.PrettyException(msg: str, /)

Base class for pretty-printable exceptions.

Parameters:
  • msg – message to format.

  • args – arguments for %-formatting the message.

Example:
class MyError(yuio.PrettyException):
    pass


try:
    ...
    raise MyError("A formatted <c b>error message</c>")
    ...
except MyError as e:
    yuio.io.error_with_tb(e)
to_colorable() Colorable

Return a colorable object with this exception’s message.

class yuio.YuioWarning

Base class for all runtime warnings.

class yuio.YuioDeprecationWarning

Base class for deprecation warnings.

class yuio.YuioPendingDeprecationWarning

Base class for pending deprecation warnings.

Magic variables

__yuio_by_name__: bool

Can be set on Enum classes to control how parse.Enum parses enum instances.

When __yuio_by_name__ is True, parsers use enumerator names to parse values; with it’s set to False, parsers use enumerator values instead.

__yuio_to_dash_case__: bool

Can be set on Enum classes to control how parse.Enum parses enum instances.

When __yuio_to_dash_case__ is True, parsers convert enumerator names/values to dash case before look up.

__yuio_doc_inline__: bool

Can be set on Enum classes to inline their Json schemas and documentation.

Useful for small enums that don’t warrant a separate section in documentation.

__yuio_short_help__: bool

Can be set on Config classes to automatically truncate parsed field help to the first paragraph. This is handy when config can be loaded from CLI, but you don’t want to show full help for every config field in CLI help message.

Environment variables

YUIO_DEBUG

When present, enables internal debug logging.

YUIO_DEBUG_FILE

When present, enables internal debug logging and specifies file to write log to.

FORCE_COLOR

When present, enables color output even if output stream is redirected or doesn’t support colors.

NO_COLOR
FORCE_NO_COLOR

When present, disables color output.

Utility functions and types

yuio.util.to_dash_case(msg: str, /) str

Convert CamelCase or snake_case identifier to a dash-case one.

This function assumes ASCII input, and will not work correctly with non-ASCII characters.

Parameters:

msg – identifier to convert.

Returns:

identifier in dash-case.

Example:
>>> to_dash_case("SomeClass")
'some-class'
>>> to_dash_case("HTTP20XMLUberParser")
'http-20-xml-uber-parser'
yuio.util.dedent(msg: str, /)

Remove leading indentation from a message and normalize trailing newlines.

This function is intended to be used with triple-quote string literals, such as docstrings. It will remove common indentation from second and subsequent lines, then it will strip any leading and trailing whitespaces and add a new line at the end.

Parameters:

msg – message to dedent.

Returns:

normalized message.

Example:
>>> def foo():
...     """Documentation for function ``foo``.
...
...     Leading indent is stripped.
...     """
...
...     ...

>>> dedent(foo.__doc__)
'Documentation for function ``foo``.\n\nLeading indent is stripped.\n'
yuio.util.find_docs(obj: Any, /) dict[str, str]

Find documentation for fields of a class.

Inspects source code of a class and finds docstrings and doc comments (#:) for variables in its body. Doesn’t inspect __init__, doesn’t return documentation for class methods.

yuio.util.commonprefix(m: Collection[str]) str
yuio.util.merge_dicts(
merge_values: Callable[[V, V], V],
/,
) Callable[[dict[K, V], dict[K, V]], dict[K, V]]

Create a function that merges two dicts, using the given callable to merge values that appear in both dicts.

Parameters:

merge_values – function that will be used to merge values that appear in both dicts.

Returns:

function that merges dicts.

Example:

This is useful for merging dicts of configs, other dicts, and so on:

merge_dicts_of_configs = merge_dicts(lambda l, r: l | r)
yuio.util.merge_dicts_opt(
merge_values: Callable[[V, V], V],
/,
) Callable[[dict[K, V] | None, dict[K, V] | None], dict[K, V] | None]

Like merge_dicts(), but also handles Nones.

class yuio.util.UserString

Base class for user string.

This class is similar to collections.UserString, but actually derived from string, with customizable wrapping semantics, and returns custom string instances from all string methods (collections.UserString doesn’t wrap strings returned from str.split() and similar).

Tip

When deriving from this class, add __slots__ to avoid making a string with a __dict__ property.

_wrap(data: str) Self

Wrap raw string that resulted from an operation on this instance into another instance of UserString.

Override this method if you need to preserve some internal state during operations.

By default, this simply creates an instance of self.__class__ with the given string.

class yuio.util.ClosedIO

Dummy stream that’s always closed.