Skip to content

Styles API

Style registry and loading system.

Registry

StyleRegistry

pyreprint.styles.registry.StyleRegistry()

Registry for named print styles.

The StyleRegistry manages a collection of named style functions that can be applied to print output. Styles can be registered programmatically or loaded from configuration files.

Example

registry = StyleRegistry() @registry.register("highlight") ... def highlight(text, **kwargs): ... return f">>> {text} <<<" styled = registry.apply("highlight", "Important") print(styled) Important <<<

Source code in pyreprint/styles/registry.py
def __init__(self) -> None:
    self._styles: Dict[str, StyleFunction] = {}

Functions

apply(name, text, **kwargs)

Apply a named style to text.

Parameters:

Name Type Description Default
name str

Name of the style.

required
text str

Text to style.

required
**kwargs Any

Additional arguments for the style function.

{}

Returns:

Type Description
str

The styled text.

Raises:

Type Description
KeyError

If the style is not found.

Source code in pyreprint/styles/registry.py
def apply(self, name: str, text: str, **kwargs: Any) -> str:
    """Apply a named style to text.

    Args:
        name: Name of the style.
        text: Text to style.
        **kwargs: Additional arguments for the style function.

    Returns:
        The styled text.

    Raises:
        KeyError: If the style is not found.
    """
    style_func = self._styles.get(name)
    if style_func is None:
        raise KeyError(f"Style '{name}' not found")
    return style_func(text, **kwargs)

clear()

Remove all registered styles.

Source code in pyreprint/styles/registry.py
def clear(self) -> None:
    """Remove all registered styles."""
    self._styles.clear()

get(name)

Get a style function by name.

Parameters:

Name Type Description Default
name str

Name of the style.

required

Returns:

Type Description
Optional[StyleFunction]

The style function, or None if not found.

Source code in pyreprint/styles/registry.py
def get(self, name: str) -> Optional[StyleFunction]:
    """Get a style function by name.

    Args:
        name: Name of the style.

    Returns:
        The style function, or None if not found.
    """
    return self._styles.get(name)

has_style(name)

Check if a style is registered.

Parameters:

Name Type Description Default
name str

Name of the style.

required

Returns:

Type Description
bool

True if the style exists.

Source code in pyreprint/styles/registry.py
def has_style(self, name: str) -> bool:
    """Check if a style is registered.

    Args:
        name: Name of the style.

    Returns:
        True if the style exists.
    """
    return name in self._styles

list_styles()

Get list of registered style names.

Returns:

Type Description
List[str]

List of style names.

Source code in pyreprint/styles/registry.py
def list_styles(self) -> List[str]:
    """Get list of registered style names.

    Returns:
        List of style names.
    """
    return list(self._styles.keys())

register(name, func=None)

Register a style function.

Can be used as a decorator or called directly.

Parameters:

Name Type Description Default
name str

Name of the style.

required
func Optional[StyleFunction]

The style function (optional if used as decorator).

None

Returns:

Type Description
Callable[[StyleFunction], StyleFunction]

The style function (for decorator usage).

Example

As decorator:

@registry.register("section") ... def section_style(text, width=60, **kwargs): ... line = "=" * width ... return f"{line}\n{text}\n{line}"

Direct registration:

registry.register("simple", lambda t, **k: f"[{t}]")

Source code in pyreprint/styles/registry.py
def register(
    self,
    name: str,
    func: Optional[StyleFunction] = None,
) -> Callable[[StyleFunction], StyleFunction]:
    """Register a style function.

    Can be used as a decorator or called directly.

    Args:
        name: Name of the style.
        func: The style function (optional if used as decorator).

    Returns:
        The style function (for decorator usage).

    Example:
        As decorator:
        >>> @registry.register("section")
        ... def section_style(text, width=60, **kwargs):
        ...     line = "=" * width
        ...     return f"{line}\\n{text}\\n{line}"

        Direct registration:
        >>> registry.register("simple", lambda t, **k: f"[{t}]")
    """
    if func is not None:
        self._styles[name] = func
        return func

    def decorator(f: StyleFunction) -> StyleFunction:
        self._styles[name] = f
        return f

    return decorator

unregister(name)

Remove a registered style.

Parameters:

Name Type Description Default
name str

Name of the style to remove.

required

Returns:

Type Description
bool

True if the style was removed, False if not found.

Source code in pyreprint/styles/registry.py
def unregister(self, name: str) -> bool:
    """Remove a registered style.

    Args:
        name: Name of the style to remove.

    Returns:
        True if the style was removed, False if not found.
    """
    if name in self._styles:
        del self._styles[name]
        return True
    return False

register_style

pyreprint.styles.registry.register_style(name, func=None)

Register a style with the global registry.

Can be used as a decorator or called directly.

Parameters:

Name Type Description Default
name str

Name of the style.

required
func Optional[StyleFunction]

The style function (optional if used as decorator).

None

Returns:

Type Description
Callable[[StyleFunction], StyleFunction]

The style function (for decorator usage).

Example

@register_style("warning") ... def warning_style(text, **kwargs): ... return f"[!] {text} [!]"

Source code in pyreprint/styles/registry.py
def register_style(
    name: str,
    func: Optional[StyleFunction] = None,
) -> Callable[[StyleFunction], StyleFunction]:
    """Register a style with the global registry.

    Can be used as a decorator or called directly.

    Args:
        name: Name of the style.
        func: The style function (optional if used as decorator).

    Returns:
        The style function (for decorator usage).

    Example:
        >>> @register_style("warning")
        ... def warning_style(text, **kwargs):
        ...     return f"[!] {text} [!]"
    """
    return registry.register(name, func)

get_style

pyreprint.styles.registry.get_style(name)

Get a style function from the global registry.

Parameters:

Name Type Description Default
name str

Name of the style.

required

Returns:

Type Description
Optional[StyleFunction]

The style function, or None if not found.

Source code in pyreprint/styles/registry.py
def get_style(name: str) -> Optional[StyleFunction]:
    """Get a style function from the global registry.

    Args:
        name: Name of the style.

    Returns:
        The style function, or None if not found.
    """
    return registry.get(name)

list_styles

pyreprint.styles.registry.list_styles()

List all registered styles in the global registry.

Returns:

Type Description
List[str]

List of style names.

Source code in pyreprint/styles/registry.py
def list_styles() -> List[str]:
    """List all registered styles in the global registry.

    Returns:
        List of style names.
    """
    return registry.list_styles()

apply_style

pyreprint.styles.registry.apply_style(name, text, **kwargs)

Apply a named style from the global registry.

Parameters:

Name Type Description Default
name str

Name of the style.

required
text str

Text to style.

required
**kwargs Any

Additional arguments for the style function.

{}

Returns:

Type Description
str

The styled text.

Raises:

Type Description
KeyError

If the style is not found.

Source code in pyreprint/styles/registry.py
def apply_style(name: str, text: str, **kwargs: Any) -> str:
    """Apply a named style from the global registry.

    Args:
        name: Name of the style.
        text: Text to style.
        **kwargs: Additional arguments for the style function.

    Returns:
        The styled text.

    Raises:
        KeyError: If the style is not found.
    """
    return registry.apply(name, text, **kwargs)

Loading

load_styles_from_file

pyreprint.styles.loader.load_styles_from_file(path, register=True)

Load styles from a YAML or TOML configuration file.

Parameters:

Name Type Description Default
path Union[str, Path]

Path to the configuration file.

required
register bool

Whether to register styles in the global registry.

True

Returns:

Type Description
Dict[str, StyleFunction]

Dictionary of style name to style function.

Raises:

Type Description
ValueError

If file format is not supported.

FileNotFoundError

If the file does not exist.

Example

styles = load_styles_from_file("my_styles.yaml")

Now you can use: reprint("Hello", style="my_custom_style")

Source code in pyreprint/styles/loader.py
def load_styles_from_file(
    path: Union[str, Path],
    register: bool = True,
) -> Dict[str, StyleFunction]:
    """Load styles from a YAML or TOML configuration file.

    Args:
        path: Path to the configuration file.
        register: Whether to register styles in the global registry.

    Returns:
        Dictionary of style name to style function.

    Raises:
        ValueError: If file format is not supported.
        FileNotFoundError: If the file does not exist.

    Example:
        >>> styles = load_styles_from_file("my_styles.yaml")
        >>> # Now you can use: reprint("Hello", style="my_custom_style")
    """
    path = Path(path)

    if not path.exists():
        raise FileNotFoundError(f"Style configuration file not found: {path}")

    content = path.read_text(encoding="utf-8")
    suffix = path.suffix.lower()

    if suffix in (".yaml", ".yml"):
        return load_styles_from_yaml(content)
    elif suffix == ".toml":
        return load_styles_from_toml(content)
    else:
        raise ValueError(f"Unsupported configuration file format: {suffix}")

load_styles_from_yaml

pyreprint.styles.loader.load_styles_from_yaml(yaml_content)

Load styles from YAML content.

Parameters:

Name Type Description Default
yaml_content str

YAML string containing style definitions.

required

Returns:

Type Description
Dict[str, StyleFunction]

Dictionary of style name to style function.

Example

yaml_content = ''' ... styles: ... divider: ... before: ... char: "-" ... width: 40 ... after: ... char: "-" ... width: 40 ... ''' styles = load_styles_from_yaml(yaml_content)

Source code in pyreprint/styles/loader.py
def load_styles_from_yaml(yaml_content: str) -> Dict[str, StyleFunction]:
    """Load styles from YAML content.

    Args:
        yaml_content: YAML string containing style definitions.

    Returns:
        Dictionary of style name to style function.

    Example:
        >>> yaml_content = '''
        ... styles:
        ...   divider:
        ...     before:
        ...       char: "-"
        ...       width: 40
        ...     after:
        ...       char: "-"
        ...       width: 40
        ... '''
        >>> styles = load_styles_from_yaml(yaml_content)
    """
    import yaml

    data = yaml.safe_load(yaml_content)
    styles: Dict[str, StyleFunction] = {}

    if not data or "styles" not in data:
        return styles

    for name, config in data.get("styles", {}).items():
        styles[name] = _create_style_from_config(config)
        # Also register in global registry
        registry.register(name, styles[name])

    return styles

load_styles_from_dict

pyreprint.styles.loader.load_styles_from_dict(config, register=True)

Load styles from a dictionary.

Parameters:

Name Type Description Default
config Dict[str, Dict[str, Any]]

Dictionary of style name to style configuration.

required
register bool

Whether to register styles in the global registry.

True

Returns:

Type Description
Dict[str, StyleFunction]

Dictionary of style name to style function.

Example

config = { ... "highlight": { ... "prefix": ">>> ", ... "suffix": " <<<", ... } ... } styles = load_styles_from_dict(config)

Source code in pyreprint/styles/loader.py
def load_styles_from_dict(
    config: Dict[str, Dict[str, Any]],
    register: bool = True,
) -> Dict[str, StyleFunction]:
    """Load styles from a dictionary.

    Args:
        config: Dictionary of style name to style configuration.
        register: Whether to register styles in the global registry.

    Returns:
        Dictionary of style name to style function.

    Example:
        >>> config = {
        ...     "highlight": {
        ...         "prefix": ">>> ",
        ...         "suffix": " <<<",
        ...     }
        ... }
        >>> styles = load_styles_from_dict(config)
    """
    styles: Dict[str, StyleFunction] = {}

    for name, style_config in config.items():
        style_func = _create_style_from_config(style_config)
        styles[name] = style_func
        if register:
            registry.register(name, style_func)

    return styles

Built-in Styles

The following styles are available by default:

Style Description
section Lines above and below text
header Text with underline
divider Softer divider with dashes
box Text surrounded by border
banner Full-width centered text
title Prominent title format
quote Blockquote style with prefix
bullet Bullet point format
numbered Numbered item format
highlight Attention markers
warning Warning message format
error Error message format
success Success message format
info Info message format