openfl.native

openfl.native package.

class openfl.native.Console(*, color_system: ~typing.Literal['auto', 'standard', '256', 'truecolor', 'windows'] | None = 'auto', force_terminal: bool | None = None, force_jupyter: bool | None = None, force_interactive: bool | None = None, soft_wrap: bool = False, theme: ~rich.theme.Theme | None = None, stderr: bool = False, file: ~typing.IO[str] | None = None, quiet: bool = False, width: int | None = None, height: int | None = None, style: str | ~rich.style.Style | None = None, no_color: bool | None = None, tab_size: int = 8, record: bool = False, markup: bool = True, emoji: bool = True, emoji_variant: ~typing.Literal['emoji', 'text'] | None = None, highlight: bool = True, log_time: bool = True, log_path: bool = True, log_time_format: str | ~typing.Callable[[~datetime.datetime], ~rich.text.Text] = '[%X]', highlighter: ~typing.Callable[[str | ~rich.text.Text], ~rich.text.Text] | None = <rich.highlighter.ReprHighlighter object>, legacy_windows: bool | None = None, safe_box: bool = True, get_datetime: ~typing.Callable[[], ~datetime.datetime] | None = None, get_time: ~typing.Callable[[], float] | None = None, _environ: ~typing.Mapping[str, str] | None = None)

A high level console interface.

Parameters:
  • color_system (str, optional) – The color system supported by your terminal, either "standard", "256" or "truecolor". Leave as "auto" to autodetect.

  • force_terminal (Optional[bool], optional) – Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.

  • force_jupyter (Optional[bool], optional) – Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.

  • force_interactive (Optional[bool], optional) – Enable/disable interactive mode, or None to auto detect. Defaults to None.

  • soft_wrap (Optional[bool], optional) – Set soft wrap default on print method. Defaults to False.

  • theme (Theme, optional) – An optional style theme object, or None for default theme.

  • stderr (bool, optional) – Use stderr rather than stdout if file is not specified. Defaults to False.

  • file (IO, optional) – A file object where the console should write to. Defaults to stdout.

  • quiet (bool, Optional) – Boolean to suppress all output. Defaults to False.

  • width (int, optional) – The width of the terminal. Leave as default to auto-detect width.

  • height (int, optional) – The height of the terminal. Leave as default to auto-detect height.

  • style (StyleType, optional) – Style to apply to all output, or None for no style. Defaults to None.

  • no_color (Optional[bool], optional) – Enabled no color mode, or None to auto detect. Defaults to None.

  • tab_size (int, optional) – Number of spaces used to replace a tab character. Defaults to 8.

  • record (bool, optional) – Boolean to enable recording of terminal output, required to call export_html(), export_svg(), and export_text(). Defaults to False.

  • markup (bool, optional) – Boolean to enable console_markup. Defaults to True.

  • emoji (bool, optional) – Enable emoji code. Defaults to True.

  • emoji_variant (str, optional) – Optional emoji variant, either “text” or “emoji”. Defaults to None.

  • highlight (bool, optional) – Enable automatic highlighting. Defaults to True.

  • log_time (bool, optional) – Boolean to enable logging of time by log() methods. Defaults to True.

  • log_path (bool, optional) – Boolean to enable the logging of the caller by log(). Defaults to True.

  • log_time_format (Union[str, TimeFormatterCallable], optional) – If log_time is enabled, either string for strftime or callable that formats the time. Defaults to “[%X] “.

  • highlighter (HighlighterType, optional) – Default highlighter.

  • legacy_windows (bool, optional) – Enable legacy Windows mode, or None to auto detect. Defaults to None.

  • safe_box (bool, optional) – Restrict box options that don’t render on legacy Windows.

  • get_datetime (Callable[[], datetime], optional) – Callable that gets the current time as a datetime.datetime object (used by Console.log), or None for datetime.now.

  • get_time (Callable[[], time], optional) – Callable that gets the current time in seconds, default uses time.monotonic.

begin_capture() None

Begin capturing console output. Call end_capture() to exit capture mode and return output.

bell() None

Play a ‘bell’ sound (if supported by the terminal).

capture() Capture

A context manager to capture the result of print() or log() in a string, rather than writing it to the console.

Example

>>> from rich.console import Console
>>> console = Console()
>>> with console.capture() as capture:
...     console.print("[bold magenta]Hello World[/]")
>>> print(capture.get())
Returns:

Capture – Context manager with disables writing to the terminal.

clear(home: bool = True) None

Clear the screen.

Parameters:

home (bool, optional) – Also move the cursor to ‘home’ position. Defaults to True.

clear_live() None

Clear the Live instance.

property color_system: str | None

Get color system string.

Returns:

Optional[str] – “standard”, “256” or “truecolor”.

control(*control: Control) None

Insert non-printing control codes.

Parameters:

control_codes (str) – Control codes, such as those that may move the cursor.

property encoding: str

Get the encoding of the console file, e.g. "utf-8".

Returns:

str – A standard encoding string.

end_capture() str

End capture mode and return captured string.

Returns:

str – Console output.

export_html(*, theme: TerminalTheme | None = None, clear: bool = True, code_format: str | None = None, inline_styles: bool = False) str

Generate HTML from console contents (requires record=True argument in constructor).

Parameters:
  • theme (TerminalTheme, optional) – TerminalTheme object containing console colors.

  • clear (bool, optional) – Clear record buffer after exporting. Defaults to True.

  • code_format (str, optional) – Format string to render HTML. In addition to ‘{foreground}’, ‘{background}’, and ‘{code}’, should contain ‘{stylesheet}’ if inline_styles is False.

  • inline_styles (bool, optional) – If True styles will be inlined in to spans, which makes files larger but easier to cut and paste markup. If False, styles will be embedded in a style tag. Defaults to False.

Returns:

str – String containing console contents as HTML.

export_svg(*, title: str = 'Rich', theme: TerminalTheme | None = None, clear: bool = True, code_format: str = '<svg class="rich-terminal" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg">\n    <!-- Generated with Rich https://www.textualize.io -->\n    <style>\n\n    @font-face {{\n        font-family: "Fira Code";\n        src: local("FiraCode-Regular"),\n                url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),\n                url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");\n        font-style: normal;\n        font-weight: 400;\n    }}\n    @font-face {{\n        font-family: "Fira Code";\n        src: local("FiraCode-Bold"),\n                url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),\n                url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");\n        font-style: bold;\n        font-weight: 700;\n    }}\n\n    .{unique_id}-matrix {{\n        font-family: Fira Code, monospace;\n        font-size: {char_height}px;\n        line-height: {line_height}px;\n        font-variant-east-asian: full-width;\n    }}\n\n    .{unique_id}-title {{\n        font-size: 18px;\n        font-weight: bold;\n        font-family: arial;\n    }}\n\n    {styles}\n    </style>\n\n    <defs>\n    <clipPath id="{unique_id}-clip-terminal">\n      <rect x="0" y="0" width="{terminal_width}" height="{terminal_height}" />\n    </clipPath>\n    {lines}\n    </defs>\n\n    {chrome}\n    <g transform="translate({terminal_x}, {terminal_y})" clip-path="url(#{unique_id}-clip-terminal)">\n    {backgrounds}\n    <g class="{unique_id}-matrix">\n    {matrix}\n    </g>\n    </g>\n</svg>\n', font_aspect_ratio: float = 0.61, unique_id: str | None = None) str

Generate an SVG from the console contents (requires record=True in Console constructor).

Parameters:
  • title (str, optional) – The title of the tab in the output image

  • theme (TerminalTheme, optional) – The TerminalTheme object to use to style the terminal

  • clear (bool, optional) – Clear record buffer after exporting. Defaults to True

  • code_format (str, optional) – Format string used to generate the SVG. Rich will inject a number of variables into the string in order to form the final SVG output. The default template used and the variables injected by Rich can be found by inspecting the console.CONSOLE_SVG_FORMAT variable.

  • font_aspect_ratio (float, optional) – The width to height ratio of the font used in the code_format string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font). If you aren’t specifying a different font inside code_format, you probably don’t need this.

  • unique_id (str, optional) – unique id that is used as the prefix for various elements (CSS styles, node ids). If not set, this defaults to a computed value based on the recorded content.

export_text(*, clear: bool = True, styles: bool = False) str

Generate text from console contents (requires record=True argument in constructor).

Parameters:
  • clear (bool, optional) – Clear record buffer after exporting. Defaults to True.

  • styles (bool, optional) – If True, ansi escape codes will be included. False for plain text. Defaults to False.

Returns:

str – String containing console contents.

property file: IO[str]

Get the file object to write to.

get_style(name: str | Style, *, default: str | Style | None = None) Style

Get a Style instance by its theme name or parse a definition.

Parameters:

name (str) – The name of a style or a style definition.

Returns:

Style – A Style object.

Raises:

MissingStyle – If no style could be parsed from name.

property height: int

Get the height of the console.

Returns:

int – The height (in lines) of the console.

input(prompt: str | Text = '', *, markup: bool = True, emoji: bool = True, password: bool = False, stream: TextIO | None = None) str

Displays a prompt and waits for input from the user. The prompt may contain color / style.

It works in the same way as Python’s builtin input() function and provides elaborate line editing and history features if Python’s builtin readline module is previously loaded.

Parameters:
  • prompt (Union[str, Text]) – Text to render in the prompt.

  • markup (bool, optional) – Enable console markup (requires a str prompt). Defaults to True.

  • emoji (bool, optional) – Enable emoji (requires a str prompt). Defaults to True.

  • password – (bool, optional): Hide typed text. Defaults to False.

  • stream – (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.

Returns:

str – Text read from stdin.

property is_alt_screen: bool

Check if the alt screen was enabled.

Returns:

bool – True if the alt screen was enabled, otherwise False.

property is_dumb_terminal: bool

Detect dumb terminal.

Returns:

bool – True if writing to a dumb terminal, otherwise False.

property is_terminal: bool

Check if the console is writing to a terminal.

Returns:
  • bool – True if the console writing to a device capable of

  • understanding terminal codes, otherwise False.

line(count: int = 1) None

Write new line(s).

Parameters:

count (int, optional) – Number of new lines. Defaults to 1.

log(*objects: Any, sep: str = ' ', end: str = '\n', style: str | Style | None = None, justify: Literal['default', 'left', 'center', 'right', 'full'] | None = None, emoji: bool | None = None, markup: bool | None = None, highlight: bool | None = None, log_locals: bool = False, _stack_offset: int = 1) None

Log rich content to the terminal.

Parameters:
  • objects (positional args) – Objects to log to the terminal.

  • sep (str, optional) – String to write between print data. Defaults to “ “.

  • end (str, optional) – String to write at end of print data. Defaults to “\n”.

  • style (Union[str, Style], optional) – A style to apply to output. Defaults to None.

  • justify (str, optional) – One of “left”, “right”, “center”, or “full”. Defaults to None.

  • emoji (Optional[bool], optional) – Enable emoji code, or None to use console default. Defaults to None.

  • markup (Optional[bool], optional) – Enable markup, or None to use console default. Defaults to None.

  • highlight (Optional[bool], optional) – Enable automatic highlighting, or None to use console default. Defaults to None.

  • log_locals (bool, optional) – Boolean to enable logging of locals where log() was called. Defaults to False.

  • _stack_offset (int, optional) – Offset of caller from end of call stack. Defaults to 1.

measure(renderable: ConsoleRenderable | RichCast | str, *, options: ConsoleOptions | None = None) Measurement

Measure a renderable. Returns a Measurement object which contains information regarding the number of characters required to print the renderable.

Parameters:
  • renderable (RenderableType) – Any renderable or string.

  • options (Optional[ConsoleOptions], optional) – Options to use when measuring, or None to use default options. Defaults to None.

Returns:

Measurement – A measurement of the renderable.

on_broken_pipe() None

This function is called when a BrokenPipeError is raised.

This can occur when piping Textual output in Linux and macOS. The default implementation is to exit the app, but you could implement this method in a subclass to change the behavior.

See https://docs.python.org/3/library/signal.html#note-on-sigpipe for details.

property options: ConsoleOptions

Get default console options.

out(*objects: Any, sep: str = ' ', end: str = '\n', style: str | Style | None = None, highlight: bool | None = None) None

Output to the terminal. This is a low-level way of writing to the terminal which unlike print() won’t pretty print, wrap text, or apply markup, but will optionally apply highlighting and a basic style.

Parameters:
  • sep (str, optional) – String to write between print data. Defaults to “ “.

  • end (str, optional) – String to write at end of print data. Defaults to “\n”.

  • style (Union[str, Style], optional) – A style to apply to output. Defaults to None.

  • highlight (Optional[bool], optional) – Enable automatic highlighting, or None to use console default. Defaults to None.

pager(pager: Pager | None = None, styles: bool = False, links: bool = False) PagerContext

A context manager to display anything printed within a “pager”. The pager application is defined by the system and will typically support at least pressing a key to scroll.

Parameters:
  • pager (Pager, optional) – A pager object, or None to use SystemPager. Defaults to None.

  • styles (bool, optional) – Show styles in pager. Defaults to False.

  • links (bool, optional) – Show links in pager. Defaults to False.

Example

>>> from rich.console import Console
>>> from rich.__main__ import make_test_card
>>> console = Console()
>>> with console.pager():
        console.print(make_test_card())
Returns:

PagerContext – A context manager.

pop_render_hook() None

Pop the last renderhook from the stack.

pop_theme() None

Remove theme from top of stack, restoring previous theme.

print(*objects: Any, sep: str = ' ', end: str = '\n', style: str | Style | None = None, justify: Literal['default', 'left', 'center', 'right', 'full'] | None = None, overflow: Literal['fold', 'crop', 'ellipsis', 'ignore'] | None = None, no_wrap: bool | None = None, emoji: bool | None = None, markup: bool | None = None, highlight: bool | None = None, width: int | None = None, height: int | None = None, crop: bool = True, soft_wrap: bool | None = None, new_line_start: bool = False) None

Print to the console.

Parameters:
  • objects (positional args) – Objects to log to the terminal.

  • sep (str, optional) – String to write between print data. Defaults to “ “.

  • end (str, optional) – String to write at end of print data. Defaults to “\n”.

  • style (Union[str, Style], optional) – A style to apply to output. Defaults to None.

  • justify (str, optional) – Justify method: “default”, “left”, “right”, “center”, or “full”. Defaults to None.

  • overflow (str, optional) – Overflow method: “ignore”, “crop”, “fold”, or “ellipsis”. Defaults to None.

  • no_wrap (Optional[bool], optional) – Disable word wrapping. Defaults to None.

  • emoji (Optional[bool], optional) – Enable emoji code, or None to use console default. Defaults to None.

  • markup (Optional[bool], optional) – Enable markup, or None to use console default. Defaults to None.

  • highlight (Optional[bool], optional) – Enable automatic highlighting, or None to use console default. Defaults to None.

  • width (Optional[int], optional) – Width of output, or None to auto-detect. Defaults to None.

  • crop (Optional[bool], optional) – Crop output to width of terminal. Defaults to True.

  • soft_wrap (bool, optional) – Enable soft wrap mode which disables word wrapping and cropping of text or None for Console default. Defaults to None.

  • new_line_start (bool, False) – Insert a new line at the start if the output contains more than one line. Defaults to False.

print_exception(*, width: int | None = 100, extra_lines: int = 3, theme: str | None = None, word_wrap: bool = False, show_locals: bool = False, suppress: Iterable[str | ModuleType] = (), max_frames: int = 100) None

Prints a rich render of the last exception and traceback.

Parameters:
  • width (Optional[int], optional) – Number of characters used to render code. Defaults to 100.

  • extra_lines (int, optional) – Additional lines of code to render. Defaults to 3.

  • theme (str, optional) – Override pygments theme used in traceback

  • word_wrap (bool, optional) – Enable word wrapping of long lines. Defaults to False.

  • show_locals (bool, optional) – Enable display of local variables. Defaults to False.

  • suppress (Iterable[Union[str, ModuleType]]) – Optional sequence of modules or paths to exclude from traceback.

  • max_frames (int) – Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.

print_json(json: str | None = None, *, data: Any | None = None, indent: None | int | str = 2, highlight: bool = True, skip_keys: bool = False, ensure_ascii: bool = False, check_circular: bool = True, allow_nan: bool = True, default: Callable[[Any], Any] | None = None, sort_keys: bool = False) None

Pretty prints JSON. Output will be valid JSON.

Parameters:
  • json (Optional[str]) – A string containing JSON.

  • data (Any) – If json is not supplied, then encode this data.

  • indent (Union[None, int, str], optional) – Number of spaces to indent. Defaults to 2.

  • highlight (bool, optional) – Enable highlighting of output: Defaults to True.

  • skip_keys (bool, optional) – Skip keys not of a basic type. Defaults to False.

  • ensure_ascii (bool, optional) – Escape all non-ascii characters. Defaults to False.

  • check_circular (bool, optional) – Check for circular references. Defaults to True.

  • allow_nan (bool, optional) – Allow NaN and Infinity values. Defaults to True.

  • default (Callable, optional) – A callable that converts values that can not be encoded in to something that can be JSON encoded. Defaults to None.

  • sort_keys (bool, optional) – Sort dictionary keys. Defaults to False.

push_render_hook(hook: RenderHook) None

Add a new render hook to the stack.

Parameters:

hook (RenderHook) – Render hook instance.

push_theme(theme: Theme, *, inherit: bool = True) None

Push a new theme on to the top of the stack, replacing the styles from the previous theme. Generally speaking, you should call use_theme() to get a context manager, rather than calling this method directly.

Parameters:
  • theme (Theme) – A theme instance.

  • inherit (bool, optional) – Inherit existing styles. Defaults to True.

render(renderable: ConsoleRenderable | RichCast | str, options: ConsoleOptions | None = None) Iterable[Segment]

Render an object in to an iterable of Segment instances.

This method contains the logic for rendering objects with the console protocol. You are unlikely to need to use it directly, unless you are extending the library.

Parameters:
  • renderable (RenderableType) – An object supporting the console protocol, or an object that may be converted to a string.

  • options (ConsoleOptions, optional) – An options object, or None to use self.options. Defaults to None.

Returns:

Iterable[Segment] – An iterable of segments that may be rendered.

render_lines(renderable: ConsoleRenderable | RichCast | str, options: ConsoleOptions | None = None, *, style: Style | None = None, pad: bool = True, new_lines: bool = False) List[List[Segment]]

Render objects in to a list of lines.

The output of render_lines is useful when further formatting of rendered console text is required, such as the Panel class which draws a border around any renderable object.

Args:

renderable (RenderableType): Any object renderable in the console. options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to None. style (Style, optional): Optional style to apply to renderables. Defaults to None. pad (bool, optional): Pad lines shorter than render width. Defaults to True. new_lines (bool, optional): Include “

“ characters at end of lines.

Returns:

List[List[Segment]]: A list of lines, where a line is a list of Segment objects.

render_str(text: str, *, style: str | Style = '', justify: Literal['default', 'left', 'center', 'right', 'full'] | None = None, overflow: Literal['fold', 'crop', 'ellipsis', 'ignore'] | None = None, emoji: bool | None = None, markup: bool | None = None, highlight: bool | None = None, highlighter: Callable[[str | Text], Text] | None = None) Text

Convert a string to a Text instance. This is called automatically if you print or log a string.

Parameters:
  • text (str) – Text to render.

  • style (Union[str, Style], optional) – Style to apply to rendered text.

  • justify (str, optional) – Justify method: “default”, “left”, “center”, “full”, or “right”. Defaults to None.

  • overflow (str, optional) – Overflow method: “crop”, “fold”, or “ellipsis”. Defaults to None.

  • emoji (Optional[bool], optional) – Enable emoji, or None to use Console default.

  • markup (Optional[bool], optional) – Enable markup, or None to use Console default.

  • highlight (Optional[bool], optional) – Enable highlighting, or None to use Console default.

  • highlighter (HighlighterType, optional) – Optional highlighter to apply.

Returns:

ConsoleRenderable – Renderable object.

rule(title: str | Text = '', *, characters: str = '─', style: str | Style = 'rule.line', align: Literal['left', 'center', 'right'] = 'center') None

Draw a line with optional centered title.

Parameters:
  • title (str, optional) – Text to render over the rule. Defaults to “”.

  • characters (str, optional) – Character(s) to form the line. Defaults to “─”.

  • style (str, optional) – Style of line. Defaults to “rule.line”.

  • align (str, optional) – How to align the title, one of “left”, “center”, or “right”. Defaults to “center”.

save_html(path: str, *, theme: TerminalTheme | None = None, clear: bool = True, code_format: str = '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<style>\n{stylesheet}\nbody {{\n    color: {foreground};\n    background-color: {background};\n}}\n</style>\n</head>\n<body>\n    <pre style="font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace"><code style="font-family:inherit">{code}</code></pre>\n</body>\n</html>\n', inline_styles: bool = False) None

Generate HTML from console contents and write to a file (requires record=True argument in constructor).

Parameters:
  • path (str) – Path to write html file.

  • theme (TerminalTheme, optional) – TerminalTheme object containing console colors.

  • clear (bool, optional) – Clear record buffer after exporting. Defaults to True.

  • code_format (str, optional) – Format string to render HTML. In addition to ‘{foreground}’, ‘{background}’, and ‘{code}’, should contain ‘{stylesheet}’ if inline_styles is False.

  • inline_styles (bool, optional) – If True styles will be inlined in to spans, which makes files larger but easier to cut and paste markup. If False, styles will be embedded in a style tag. Defaults to False.

save_svg(path: str, *, title: str = 'Rich', theme: TerminalTheme | None = None, clear: bool = True, code_format: str = '<svg class="rich-terminal" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg">\n    <!-- Generated with Rich https://www.textualize.io -->\n    <style>\n\n    @font-face {{\n        font-family: "Fira Code";\n        src: local("FiraCode-Regular"),\n                url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),\n                url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");\n        font-style: normal;\n        font-weight: 400;\n    }}\n    @font-face {{\n        font-family: "Fira Code";\n        src: local("FiraCode-Bold"),\n                url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),\n                url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");\n        font-style: bold;\n        font-weight: 700;\n    }}\n\n    .{unique_id}-matrix {{\n        font-family: Fira Code, monospace;\n        font-size: {char_height}px;\n        line-height: {line_height}px;\n        font-variant-east-asian: full-width;\n    }}\n\n    .{unique_id}-title {{\n        font-size: 18px;\n        font-weight: bold;\n        font-family: arial;\n    }}\n\n    {styles}\n    </style>\n\n    <defs>\n    <clipPath id="{unique_id}-clip-terminal">\n      <rect x="0" y="0" width="{terminal_width}" height="{terminal_height}" />\n    </clipPath>\n    {lines}\n    </defs>\n\n    {chrome}\n    <g transform="translate({terminal_x}, {terminal_y})" clip-path="url(#{unique_id}-clip-terminal)">\n    {backgrounds}\n    <g class="{unique_id}-matrix">\n    {matrix}\n    </g>\n    </g>\n</svg>\n', font_aspect_ratio: float = 0.61, unique_id: str | None = None) None

Generate an SVG file from the console contents (requires record=True in Console constructor).

Parameters:
  • path (str) – The path to write the SVG to.

  • title (str, optional) – The title of the tab in the output image

  • theme (TerminalTheme, optional) – The TerminalTheme object to use to style the terminal

  • clear (bool, optional) – Clear record buffer after exporting. Defaults to True

  • code_format (str, optional) – Format string used to generate the SVG. Rich will inject a number of variables into the string in order to form the final SVG output. The default template used and the variables injected by Rich can be found by inspecting the console.CONSOLE_SVG_FORMAT variable.

  • font_aspect_ratio (float, optional) – The width to height ratio of the font used in the code_format string. Defaults to 0.61, which is the width to height ratio of Fira Code (the default font). If you aren’t specifying a different font inside code_format, you probably don’t need this.

  • unique_id (str, optional) – unique id that is used as the prefix for various elements (CSS styles, node ids). If not set, this defaults to a computed value based on the recorded content.

save_text(path: str, *, clear: bool = True, styles: bool = False) None

Generate text from console and save to a given location (requires record=True argument in constructor).

Parameters:
  • path (str) – Path to write text files.

  • clear (bool, optional) – Clear record buffer after exporting. Defaults to True.

  • styles (bool, optional) – If True, ansi style codes will be included. False for plain text. Defaults to False.

screen(hide_cursor: bool = True, style: str | Style | None = None) ScreenContext

Context manager to enable and disable ‘alternative screen’ mode.

Parameters:
  • hide_cursor (bool, optional) – Also hide the cursor. Defaults to False.

  • style (Style, optional) – Optional style for screen. Defaults to None.

Returns:

~ScreenContext – Context which enables alternate screen on enter, and disables it on exit.

set_alt_screen(enable: bool = True) bool

Enables alternative screen mode.

Note, if you enable this mode, you should ensure that is disabled before the application exits. See screen() for a context manager that handles this for you.

Parameters:

enable (bool, optional) – Enable (True) or disable (False) alternate screen. Defaults to True.

Returns:

bool – True if the control codes were written.

set_live(live: Live) None

Set Live instance. Used by Live context manager.

Parameters:

live (Live) – Live instance using this Console.

Raises:

errors.LiveError – If this Console has a Live context currently active.

set_window_title(title: str) bool

Set the title of the console terminal window.

Warning: There is no means within Rich of “resetting” the window title to its previous value, meaning the title you set will persist even after your application exits.

fish shell resets the window title before and after each command by default, negating this issue. Windows Terminal and command prompt will also reset the title for you. Most other shells and terminals, however, do not do this.

Some terminals may require configuration changes before you can set the title. Some terminals may not support setting the title at all.

Other software (including the terminal itself, the shell, custom prompts, plugins, etc.) may also set the terminal window title. This could result in whatever value you write using this method being overwritten.

Parameters:

title (str) – The new title of the terminal window.

Returns:

bool – True if the control code to change the terminal title was written, otherwise False. Note that a return value of True does not guarantee that the window title has actually changed, since the feature may be unsupported/disabled in some terminals.

show_cursor(show: bool = True) bool

Show or hide the cursor.

Parameters:

show (bool, optional) – Set visibility of the cursor.

property size: ConsoleDimensions

Get the size of the console.

Returns:

ConsoleDimensions – A named tuple containing the dimensions.

status(status: ConsoleRenderable | RichCast | str, *, spinner: str = 'dots', spinner_style: str | Style = 'status.spinner', speed: float = 1.0, refresh_per_second: float = 12.5) Status

Display a status and spinner.

Parameters:
  • status (RenderableType) – A status renderable (str or Text typically).

  • spinner (str, optional) – Name of spinner animation (see python -m rich.spinner). Defaults to “dots”.

  • spinner_style (StyleType, optional) – Style of spinner. Defaults to “status.spinner”.

  • speed (float, optional) – Speed factor for spinner animation. Defaults to 1.0.

  • refresh_per_second (float, optional) – Number of refreshes per second. Defaults to 12.5.

Returns:

Status – A Status object that may be used as a context manager.

update_screen(renderable: ConsoleRenderable | RichCast | str, *, region: Region | None = None, options: ConsoleOptions | None = None) None

Update the screen at a given offset.

Parameters:
  • renderable (RenderableType) – A Rich renderable.

  • region (Region, optional) – Region of screen to update, or None for entire screen. Defaults to None.

  • x (int, optional) – x offset. Defaults to 0.

  • y (int, optional) – y offset. Defaults to 0.

Raises:

errors.NoAltScreen – If the Console isn’t in alt screen mode.

update_screen_lines(lines: List[List[Segment]], x: int = 0, y: int = 0) None

Update lines of the screen at a given offset.

Parameters:
  • lines (List[List[Segment]]) – Rendered lines (as produced by render_lines()).

  • x (int, optional) – x offset (column no). Defaults to 0.

  • y (int, optional) – y offset (column no). Defaults to 0.

Raises:

errors.NoAltScreen – If the Console isn’t in alt screen mode.

use_theme(theme: Theme, *, inherit: bool = True) ThemeContext

Use a different theme for the duration of the context manager.

Parameters:
  • theme (Theme) – Theme instance to user.

  • inherit (bool, optional) – Inherit existing console styles. Defaults to True.

Returns:

ThemeContext – [description]

property width: int

Get the width of the console.

Returns:

int – The width (in characters) of the console.

class openfl.native.Path(*args, **kwargs)

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

absolute()

Return an absolute version of this path. This function works even if the path doesn’t point to anything.

No normalization is done, i.e. all ‘.’ and ‘..’ will be kept along. Use resolve() to get the canonical path to a file.

chmod(mode, *, follow_symlinks=True)

Change the permissions of the path, like os.chmod().

classmethod cwd()

Return a new path pointing to the current working directory (as returned by os.getcwd()).

exists()

Whether this path exists.

expanduser()

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

glob(pattern)

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

group()

Return the group name of the file gid.

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

classmethod home()

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

is_block_device()

Whether this path is a block device.

is_char_device()

Whether this path is a character device.

is_dir()

Whether this path is a directory.

is_fifo()

Whether this path is a FIFO.

is_file()

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()

Check if this path is a POSIX mount point

is_socket()

Whether this path is a socket.

Whether this path is a symbolic link.

iterdir()

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

lchmod(mode)

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

Make the target path a hard link pointing to this path.

Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.

Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.

lstat()

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

mkdir(mode=511, parents=False, exist_ok=False)

Create a new directory at this given path.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

Open the file pointed by this path and return a file object, as the built-in open() function does.

owner()

Return the login name of the file owner.

read_bytes()

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)

Open the file in text mode, read it, and close the file.

Return the path to which the symbolic link points.

rename(target)

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

resolve(strict=False)

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows).

rglob(pattern)

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

rmdir()

Remove this directory. The directory must be empty.

samefile(other_path)

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

stat(*, follow_symlinks=True)

Return the result of the stat() system call on this path, like os.stat() does.

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

touch(mode=438, exist_ok=True)

Create this file with the given access mode, if it doesn’t exist.

Remove this file or link. If the path is a directory, use rmdir() instead.

write_bytes(data)

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)

Open the file in text mode, write to it, and close the file.

class openfl.native.Plan

A class used to represent a Federated Learning plan.

This class provides methods to manage and manipulate federated learning plans.

Class Attributes:
  • logger (Logger) – Logger instance for the class.

  • config (dict) – Dictionary containing patched plan definition.

  • authorized_cols (list) – Authorized collaborator list.

  • cols_data_paths (dict) – Collaborator data paths dictionary.

  • collaborator_ (Collaborator) – Collaborator object.

  • aggregator_ (Aggregator) – Aggregator object.

  • assigner_ (Assigner) – Assigner object.

  • loader_ (DataLoader) – Data loader object.

  • runner_ (TaskRunner) – Task runner object.

  • server_ (AggregatorGRPCServer) – gRPC server object.

  • client_ (AggregatorGRPCClient) – gRPC client object.

  • pipe_ (CompressionPipeline) – Compression pipeline object.

  • straggler_policy_ (StragglerHandlingPolicy) – Straggler handling policy.

  • hash_ (str) – Hash of the instance.

  • name_ (str) – Name of the instance.

  • serializer_ (SerializerPlugin) – Serializer plugin.

static build(template, settings, **override)

Create an instance of a openfl Component or Federated DataLoader/TaskRunner.

Parameters:
  • template (str) – Fully qualified class template path.

  • settings (dict) – Keyword arguments to class constructor.

  • override (dict) – Additional settings to override the default ones.

Returns:

object – A Python object.

deserialize_interface_objects()

Deserialize objects for TaskRunner.

Returns:

tuple – Tuple containing the deserialized objects.

static dump(yaml_path, config, freeze=False)

Dump the plan config to YAML file.

Parameters:
  • yaml_path (Path) – Path to the YAML file.

  • config (dict) – Plan configuration to be dumped.

  • freeze (bool, optional) – Flag to freeze the plan. Defaults to False.

get_aggregator(tensor_dict=None)

Get federation aggregator.

This method retrieves the federation aggregator. If the aggregator does not exist, it is built using the configuration settings and the provided tensor dictionary.

Parameters:

tensor_dict (dict, optional) – The initial tensor dictionary to use when building the aggregator. Defaults to None.

Returns:

self.aggregator_ (Aggregator) – The federation aggregator.

Raises:

TypeError – If the log_metric_callback is not a callable object or cannot be imported from code.

get_assigner()

Get the plan task assigner.

get_client(collaborator_name, aggregator_uuid, federation_uuid, root_certificate=None, private_key=None, certificate=None)

Get gRPC client for the specified collaborator.

Parameters:
  • collaborator_name (str) – Name of the collaborator.

  • aggregator_uuid (str) – UUID of the aggregator.

  • federation_uuid (str) – UUID of the federation.

  • root_certificate (str, optional) – Root certificate for the collaborator. Defaults to None.

  • private_key (str, optional) – Private key for the collaborator. Defaults to None.

  • certificate (str, optional) – Certificate for the collaborator. Defaults to None.

Returns:

AggregatorGRPCClient – gRPC client for the specified collaborator.

get_collaborator(collaborator_name, root_certificate=None, private_key=None, certificate=None, task_runner=None, client=None, shard_descriptor=None)

Get collaborator.

This method retrieves a collaborator. If the collaborator does not exist, it is built using the configuration settings and the provided parameters.

Parameters:
  • collaborator_name (str) – Name of the collaborator.

  • root_certificate (str, optional) – Root certificate for the collaborator. Defaults to None.

  • private_key (str, optional) – Private key for the collaborator. Defaults to None.

  • certificate (str, optional) – Certificate for the collaborator. Defaults to None.

  • task_runner (TaskRunner, optional) – Task runner for the collaborator. Defaults to None.

  • client (Client, optional) – Client for the collaborator. Defaults to None.

  • shard_descriptor (ShardDescriptor, optional) – Descriptor of the data shard. Defaults to None.

Returns:

self.collaborator_ (Collaborator) – The collaborator instance.

get_core_task_runner(data_loader=None, model_provider=None, task_keeper=None)

Get core task runner.

Parameters:
  • data_loader (DataLoader, optional) – Data loader for the tasks. Defaults to None.

  • model_provider (ModelProvider, optional) – Provider for the model. Defaults to None.

  • task_keeper (TaskKeeper, optional) – Keeper for the tasks. Defaults to None.

Returns:

CoreTaskRunner – Core task runner for the tasks.

get_data_loader(collaborator_name)

Get data loader for a specific collaborator.

Parameters:

collaborator_name (str) – Name of the collaborator.

Returns:

DataLoader – Data loader for the specified collaborator.

get_serializer_plugin(**kwargs)

Get serializer plugin.

This plugin is used for serialization of interfaces in new interactive API.

Parameters:

**kwargs – Additional keyword arguments.

Returns:

SerializerPlugin – Serializer plugin.

get_server(root_certificate=None, private_key=None, certificate=None, **kwargs)

Get gRPC server of the aggregator instance.

Parameters:
  • root_certificate (str, optional) – Root certificate for the server. Defaults to None.

  • private_key (str, optional) – Private key for the server. Defaults to None.

  • certificate (str, optional) – Certificate for the server. Defaults to None.

  • **kwargs – Additional keyword arguments.

Returns:

AggregatorGRPCServer – gRPC server of the aggregator instance.

get_straggler_handling_policy()

Get straggler handling policy.

get_task_runner(data_loader)

Get task runner.

Parameters:

data_loader (DataLoader) – Data loader for the tasks.

Returns:

TaskRunner – Task runner for the tasks.

get_tasks()

Get federation tasks.

get_tensor_pipe()

Get data tensor pipeline.

property hash

Generate hash for this instance.

static import_(template)

Import an instance of a openfl Component or Federated DataLoader/TaskRunner.

Parameters:

template (str) – Fully qualified object path.

Returns:

object – A Python object.

initialize_data_loader(data_loader, shard_descriptor)

Initialize data loader.

Parameters:
  • data_loader (DataLoader) – Data loader to initialize.

  • shard_descriptor (ShardDescriptor) – Descriptor of the data shard.

Returns:

DataLoader – Initialized data loader.

interactive_api_get_server(*, tensor_dict, root_certificate, certificate, private_key, tls)

Get gRPC server of the aggregator instance for interactive API.

Parameters:
  • tensor_dict (dict) – Dictionary of tensors.

  • root_certificate (str) – Root certificate for the server.

  • certificate (str) – Certificate for the server.

  • private_key (str) – Private key for the server.

  • tls (bool) – Whether to use Transport Layer Security.

Returns:

AggregatorGRPCServer – gRPC server of the aggregator instance.

static load(yaml_path: Path, default: dict | None = None)

Load the plan from YAML file.

Parameters:
  • yaml_path (Path) – Path to the YAML file.

  • default (dict, optional) – Default plan configuration. Defaults to {}.

Returns:

dict – Plan configuration loaded from the YAML file.

static parse(plan_config_path: Path, cols_config_path: Path | None = None, data_config_path: Path | None = None, gandlf_config_path=None, resolve=True)

Parse the Federated Learning plan.

Parameters:
  • plan_config_path (Path) – The filepath to the Federated Learning plan.

  • cols_config_path (Path, optional) – The filepath to the Federation collaborator list. Defaults to None.

  • data_config_path (Path, optional) – The filepath to the Federation collaborator data configuration. Defaults to None.

  • gandlf_config_path (Path, optional) – The filepath to a yaml file that overrides the configuration. Defaults to None.

  • resolve (bool, optional) – Flag to resolve the plan settings. Defaults to True.

Returns:

Plan – A Federated Learning plan object.

resolve()

Resolve the federation settings.

restore_object(filename)

Deserialize an object.

Parameters:

filename (str) – Name of the file.

Returns:

object – Deserialized object.

class openfl.native.RichHandler(level: int | str = 0, console: Console | None = None, *, show_time: bool = True, omit_repeated_times: bool = True, show_level: bool = True, show_path: bool = True, enable_link_path: bool = True, highlighter: Highlighter | None = None, markup: bool = False, rich_tracebacks: bool = False, tracebacks_width: int | None = None, tracebacks_code_width: int = 88, tracebacks_extra_lines: int = 3, tracebacks_theme: str | None = None, tracebacks_word_wrap: bool = True, tracebacks_show_locals: bool = False, tracebacks_suppress: Iterable[str | ModuleType] = (), tracebacks_max_frames: int = 100, locals_max_length: int = 10, locals_max_string: int = 80, log_time_format: str | Callable[[datetime], Text] = '[%x %X]', keywords: List[str] | None = None)

A logging handler that renders output with Rich. The time / level / message and file are displayed in columns. The level is color coded, and the message is syntax highlighted.

Note

Be careful when enabling console markup in log messages if you have configured logging for libraries not under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.

Parameters:
  • level (Union[int, str], optional) – Log level. Defaults to logging.NOTSET.

  • console (Console, optional) – Optional console instance to write logs. Default will use a global console instance writing to stdout.

  • show_time (bool, optional) – Show a column for the time. Defaults to True.

  • omit_repeated_times (bool, optional) – Omit repetition of the same time. Defaults to True.

  • show_level (bool, optional) – Show a column for the level. Defaults to True.

  • show_path (bool, optional) – Show the path to the original log call. Defaults to True.

  • enable_link_path (bool, optional) – Enable terminal link of path column to file. Defaults to True.

  • highlighter (Highlighter, optional) – Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.

  • markup (bool, optional) – Enable console markup in log messages. Defaults to False.

  • rich_tracebacks (bool, optional) – Enable rich tracebacks with syntax highlighting and formatting. Defaults to False.

  • tracebacks_width (Optional[int], optional) – Number of characters used to render tracebacks, or None for full width. Defaults to None.

  • tracebacks_code_width (int, optional) – Number of code characters used to render tracebacks, or None for full width. Defaults to 88.

  • tracebacks_extra_lines (int, optional) – Additional lines of code to render tracebacks, or None for full width. Defaults to None.

  • tracebacks_theme (str, optional) – Override pygments theme used in traceback.

  • tracebacks_word_wrap (bool, optional) – Enable word wrapping of long tracebacks lines. Defaults to True.

  • tracebacks_show_locals (bool, optional) – Enable display of locals in tracebacks. Defaults to False.

  • tracebacks_suppress (Sequence[Union[str, ModuleType]]) – Optional sequence of modules or paths to exclude from traceback.

  • tracebacks_max_frames (int, optional) – Optional maximum number of frames returned by traceback.

  • locals_max_length (int, optional) – Maximum length of containers before abbreviating, or None for no abbreviation. Defaults to 10.

  • locals_max_string (int, optional) – Maximum length of string before truncating, or None to disable. Defaults to 80.

  • log_time_format (Union[str, TimeFormatterCallable], optional) – If log_time is enabled, either string for strftime or callable that formats the time. Defaults to “[%x %X] “.

  • keywords (List[str], optional) – List of words to highlight instead of RichHandler.KEYWORDS.

HIGHLIGHTER_CLASS

alias of ReprHighlighter

emit(record: LogRecord) None

Invoked by logging.

get_level_text(record: LogRecord) Text

Get the level name from the record.

Parameters:

record (LogRecord) – LogRecord instance.

Returns:

Text – A tuple of the style and level name.

render(*, record: LogRecord, traceback: Traceback | None, message_renderable: ConsoleRenderable) ConsoleRenderable

Render log for display.

Parameters:
  • record (LogRecord) – logging Record.

  • traceback (Optional[Traceback]) – Traceback instance or None for no Traceback.

  • message_renderable (ConsoleRenderable) – Renderable (typically Text) containing log message contents.

Returns:

ConsoleRenderable – Renderable to display log.

render_message(record: LogRecord, message: str) ConsoleRenderable

Render message text in to Text.

Parameters:
  • record (LogRecord) – logging Record.

  • message (str) – String containing log message.

Returns:

ConsoleRenderable – Renderable to display log message.

openfl.native.add_log_level(level_name, level_num, method_name=None)

Add a new logging level to the logging module.

This function adds a new logging level to the logging module with a specified name, value, and method name.

Parameters:
  • level_name (str) – The name of the new logging level.

  • level_num (int) – The value of the new logging level.

  • method_name (str, optional) – The name of the method to use for the new logging level. Defaults to None.

openfl.native.basicConfig(**kwargs)

Do basic configuration for the logging system.

This function does nothing if the root logger already has handlers configured, unless the keyword argument force is set to True. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package.

The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger.

A number of optional keyword arguments may be specified, which can alter the default behaviour.

filename Specifies that a FileHandler be created, using the specified

filename, rather than a StreamHandler.

filemode Specifies the mode to open the file, if filename is specified

(if filemode is unspecified, it defaults to ‘a’).

format Use the specified format string for the handler. datefmt Use the specified date/time format. style If a format string is specified, use this to specify the

type of format string (possible values ‘%’, ‘{’, ‘$’, for %-formatting, str.format() and string.Template - defaults to ‘%’).

level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note

that this argument is incompatible with ‘filename’ - if both are present, ‘stream’ is ignored.

handlers If specified, this should be an iterable of already created

handlers, which will be added to the root handler. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function.

force If this keyword is specified as true, any existing handlers

attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.

encoding If specified together with a filename, this encoding is passed to

the created FileHandler, causing it to be used when the file is opened.

errors If specified together with a filename, this value is passed to the

created FileHandler, causing it to be used when the file is opened in text mode. If not specified, the default value is backslashreplace.

Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed.

Changed in version 3.2: Added the style parameter.

Changed in version 3.3: Added the handlers parameter. A ValueError is now thrown for incompatible arguments (e.g. handlers specified together with filename/filemode, or filename/filemode specified together with stream, or handlers specified together with stream.

Changed in version 3.8: Added the force parameter.

Changed in version 3.9: Added the encoding and errors parameters.

openfl.native.copy(x)

Shallow copy operation on arbitrary Python objects.

See the module’s __doc__ string for more info.

openfl.native.flatten(config, return_complete=False)

Flatten nested config.

Parameters:
  • config (dict) – The configuration dictionary to flatten.

  • return_complete (bool, optional) – Whether to return the complete flattened config. Defaults to False.

Returns:

flattened_config (dict) – The flattened configuration dictionary.

openfl.native.getLogger(name=None)

Return a logger with the specified name, creating it if necessary.

If no name is specified, return the root logger.

openfl.native.get_collaborator(plan, name, model, aggregator)

Create the collaborator.

Using the same plan object to create multiple collaborators leads to identical collaborator objects. This function can be removed once collaborator generation is fixed in openfl/federated/plan/plan.py

Parameters:
  • plan (Plan) – The plan to use to create the collaborator.

  • name (str) – The name of the collaborator.

  • model (Model) – The model to use for the collaborator.

  • aggregator (Aggregator) – The aggregator to use for the collaborator.

Returns:

Collaborator – The created collaborator.

openfl.native.get_plan(fl_plan=None, indent=4, sort_keys=True)

Returns a string representation of the current Plan.

Parameters:
  • fl_plan (Plan) – The plan to get a string representation of. If None, a new plan is set up. Defaults to None.

  • indent (int) – The number of spaces to use for indentation in the string representation. Defaults to 4.

  • sort_keys (bool) – Whether to sort the keys in the string representation. Defaults to True.

Returns:

str – A string representation of the plan.

openfl.native.init(workspace_template: str = 'default', log_level: str = 'INFO', log_file: str | None = None, agg_fqdn: str | None = None, col_names=None)

Initialize the openfl package.

It performs the following tasks:

1. Creates a workspace in ~/.local/workspace (Equivalent to fx workspace create –prefix ~/.local/workspace –template $workspace_template) 2. Setup certificate authority (equivalent to `fx workspace certify) 3. Setup aggregator PKI (equivalent to fx aggregator generate-cert-request followed by fx aggregator certify) 4. Setup list of collaborators (col_names) and their PKI. (Equivalent to running fx collaborator generate-cert-request followed by fx collaborator certify for each of the collaborators in col_names) 5. Setup logging

Parameters:
  • workspace_template (str) – The template that should be used as the basis for the experiment. Defaults to ‘default’. Other options include are any of the template names [keras_cnn_mnist, tf_2dunet, tf_cnn_histology, mtorch_cnn_histology, torch_cnn_mnist].

  • log_level (str) – Log level for logging. METRIC level is available. Defaults to ‘INFO’.

  • log_file (str) – Name of the file in which the log will be duplicated. If None, logs are not saved to a file. Defaults to None.

  • agg_fqdn (str) – The local node’s fully qualified domain name (if it can’t be resolved automatically). Defaults to None.

  • col_names (list[str]) – The names of the collaborators that will be created. These collaborators will be set up to participate in the experiment, but are not required to. Defaults to None.

Returns:

None

openfl.native.run_experiment(collaborator_dict: dict, override_config: dict | None = None)

Core function that executes the FL Plan.

Parameters:
  • collaborator_dict (dict) – A dictionary mapping collaborator names to their federated models. Example: {collaborator_name(str): FederatedModel} This dictionary defines which collaborators will participate in the experiment, as well as a reference to that collaborator’s federated model.

  • override_config (dict, optional) – A dictionary of values to override in the plan. Defaults to None. Example: dict {flplan.key : flplan.value} Override any of the plan parameters at runtime using this dictionary. To get a list of the available options, execute fx.get_plan()

Returns:

model – Final Federated model. The model resulting from the federated learning experiment

openfl.native.setup_logging(level='INFO', log_file=None)

Initializes logging settings.

Parameters:
  • level (str, optional) – The log level. Defaults to ‘INFO’.

  • log_file (str, optional) – The name of the file to log to.

  • None (If)

  • None. (logs are not saved to a file. Defaults to)

openfl.native.setup_plan(log_level='CRITICAL')

Dump the plan with all defaults + overrides set.

Parameters:
  • log_level (str, optional) – The log level Whether to save the plan to disk.

  • 'CRITICAL'. (Defaults to)

Returns:

plan – Plan object.

openfl.native.split_tensor_dict_for_holdouts(logger, tensor_dict, keep_types=(<class 'numpy.floating'>, <class 'numpy.integer'>), holdout_tensor_names=())

Split a tensor according to tensor types.

This function splits a tensor dictionary into two dictionaries: one containing the tensors to send and the other containing the holdout tensors.

Parameters:
  • logger (Logger) – The logger to use for reporting warnings.

  • tensor_dict (dict) – A dictionary of tensors.

  • keep_types (Tuple[type, ...], optional) – A tuple of types to keep in the dictionary of tensors. Defaults to (np.floating, np.integer).

  • holdout_tensor_names (Iterable[str], optional) – An iterable of tensor names to extract from the dictionary of tensors. Defaults to ().

Returns:

Tuple[dict, dict] – The first dictionary is the original tensor dictionary minus the holdout tensors and the second dictionary is a tensor dictionary with only the holdout tensors.

openfl.native.unflatten(config, separator='.')

Unfolds config settings that have separator in their names.

Parameters:
  • config (dict) – The flattened configuration dictionary to unfold.

  • separator (str, optional) – The separator used in the flattened config. Defaults to ‘.’.

Returns:

config (dict) – The unfolded configuration dictionary.

openfl.native.update_plan(override_config, plan=None, resolve=True)

Updates the plan with the provided override and saves it to disk.

For a list of available override options, call fx.get_plan()

Parameters:
  • override_config (dict) – A dictionary of values to override in the plan.

  • plan (Plan, optional) – The plan to update. If None, a new plan is set up. Defaults to None.

  • resolve (bool, optional) – Whether to resolve the plan. Defaults to True.

Returns:

plan (object) – The updated plan.

native

OpenFL Native functions module.