Skip to content

pyparam.utils

module

pyparam.utils

Utilities for pyparam

Attributes
  • logger The logger
Classes
  • Namespace Subclass of argparse.Namespace</>
  • Codeblock A code block, will be rendered as rich.syntax.Syntax</>
  • RichHandler Subclass of rich.logging.RichHandler, showing log levels as a single character</>
Functions
  • always_list(str_or_list, strip, split) (list of str) Convert a string (comma separated) or a list to a list</>
  • cast_to(value, to_type) (any) Cast a value to a given type</>
  • parse_potential_argument(arg, prefix, allow_attached) (str, str, str) Parse a potential argument with given prefix</>
  • parse_type(typestr) (list of str) Parse the type string</>
  • type_from_value(value) (str) Detect parameter type from a value</>
class

pyparam.utils.Namespace(**kwargs)

Bases
argparse.Namespace argparse._AttributeHolder

Subclass of argparse.Namespace

We have enabled __getitem__, __setitem__, __len__ and __contains__. So that you can do:

ns = Namespace()
ns['a'] = 1  # same as ns.a = 1
ns['a'] == 1 # same as ns.a == 1
len(ns) == 1
'a' in ns
Attributes
  • __command__ The command name if matched.
class

pyparam.utils.Codeblock(opentag, lang, indent, codes=None)

A code block, will be rendered as rich.syntax.Syntax

Methods
  • add_code(code) Add code to code block</>
  • is_end(line) (bool) Tell if the line is the end of the code block</>
  • render() (Padding) Render the code block to a rich.syntax.Syntax</>
  • scan(maybe_codeblock, check_default) (list of str or Codeblock, Codeblock) Scan and try to create codeblock objects from maybe_codeblock</>
  • scan_texts(texts, check_default) (list of str or Codeblock) Scan multiple texts for code blocks</>
classmethod

scan_texts(texts, check_default=False)

Scan multiple texts for code blocks

Parameters
  • texts (list of str) a list of texts
  • check_default (bool, optional) Check if there is default in maybe_codeblock. Defaults should not be scanned as code blocks
  • cls (Codeblock class) The class
Returns (list of str or Codeblock)

mixed text and code blocks

classmethod

scan(maybe_codeblock, check_default=False)

Scan and try to create codeblock objects from maybe_codeblock

Parameters
  • maybe_codeblock (str) Maybe a code block start It can be a text block, we have to scan if it has code blocks inside.
  • check_default (bool, optional) Check if there is default in maybe_codeblock. Defaults should not be scanned as code blocks
  • cls (Codeblock class) The class
Returns (list of str or Codeblock, Codeblock)

mixed text and unclosed code blocks

method

add_code(code)

Add code to code block

Parameters
  • code (str) code to add It can be multiple lines, each of which will be dedented
method

is_end(line)

Tell if the line is the end of the code block

Parameters
  • line (str) line to check
Returns (bool)

True if it is the end otherwise False

method

render()

Render the code block to a rich.syntax.Syntax

Returns (Padding)

A padding of rich.syntax.Syntax

function

pyparam.utils.always_list(str_or_list, strip=True, split=',') → list of str

Convert a string (comma separated) or a list to a list

Parameters
  • str_or_list (Union(str, list of str)) string or list
  • strip (bool, optional) whether to strip the elements in result list
  • split (str or bool, optional) Delimiter for split or False to not split

Return: list: list of strings

function

pyparam.utils.parse_type(typestr)

Parse the type string

Examples
>>> parse_type(None)    # None, None
>>> parse_type("array") # list, None
>>> parse_type("a:i")   # list, int
>>> parse_type("j")     # json, None
>>> parse_type("list")  # list, None
Parameters
  • typestr (str) string of type to parse
Returns (list of str)

Main type and subtype

Raises
  • PyParamTypeError When a type cannot be parsed
function

pyparam.utils.parse_potential_argument(arg, prefix, allow_attached=False)

Parse a potential argument with given prefix

Examples
>>> # prefix == 'auto
>>> parse_potential_argument("-a")     # a, None, None
>>> parse_potential_argument("--arg")  # arg, None, None
>>> parse_potential_argument("--a")    # None, None, a
>>> parse_potential_argument("-abc")   # None, None, -abc
>>> parse_potential_argument("-abc", allow_attached=True)
>>> # -a, None, bc
Parameters
  • arg (str) a potential argument. Such as: -a, --def, -b=1, --abc=value, -b1 (for argument -b with value 1) with types: -a:int --def:list -b:str=1 --abs:str=value -b:bool It is usually one element of the sys.argv
  • prefix (str) The prefix for the argument names
  • allow_attached (bool, optional) Whether to detect item like '-b1' for argument '-b' with value '1' or the entire one is parsed as argument '-b1'
Returns (str, str, str)

The argument name, type and value When arg cannot be parsed as an argument, argument name and type will both be None. arg will be returned as argument value.

function

pyparam.utils.type_from_value(value)

Detect parameter type from a value

Parameters
  • value (any) The value
Returns (str)

The name of the type

Raises
  • PyParamTypeError When we have list as subtype. For example, when value is [[1]]
function

pyparam.utils.cast_to(value, to_type)

Cast a value to a given type

Parameters
  • value (any) value to cast
  • to_type (str or bool) type to cast
Returns (any)

casted value

Raises
  • PyParamTypeError if value is not able to be casted
class

pyparam.utils.RichHandler(level=0, console=None, show_time=True, omit_repeated_times=True, show_level=True, show_path=True, enable_link_path=True, highlighter=None, markup=False, rich_tracebacks=False, tracebacks_width=None, tracebacks_extra_lines=3, tracebacks_theme=None, tracebacks_word_wrap=True, tracebacks_show_locals=False, tracebacks_suppress=(), locals_max_length=10, locals_max_string=80, log_time_format='[%x %X]', keywords=None)

Bases
rich.logging.RichHandler logging.Handler logging.Filterer

Subclass of rich.logging.RichHandler, showing log levels as a single character

Parameters
  • level (int or str, optional) Log level. Defaults to logging.NOTSET.
  • 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 (int, optional) Number of characters used to render tracebacks, or None for full width. Defaults to None.
  • 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 (iterable of str or module, optional) Optional sequence of modules or paths to exclude from 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, callable(datetime: text)), optional) If log_time is enabled, either string for strftime or callable that formats the time. Defaults to "[%x %X] ".
  • keywords (list of str, optional) List of words to highlight instead of RichHandler.KEYWORDS.
Methods
  • acquire() Acquire the I/O thread lock.</>
  • addFilter(filter) Add the specified filter to this handler.</>
  • close() Tidy up any resources used by the handler.</>
  • createLock() Acquire a thread lock for serializing access to the underlying I/O.</>
  • emit(record) Invoked by logging.</>
  • filter(record) Determine if a record is loggable by consulting all the filters.</>
  • flush() Ensure all logging output has been flushed.</>
  • format(record) Format the specified record.</>
  • get_level_text(record) (Text) Get the level name from the record.</>
  • handle(record) Conditionally emit the specified logging record.</>
  • handleError(record) Handle errors which occur during an emit() call.</>
  • release() Release the I/O thread lock.</>
  • removeFilter(filter) Remove the specified filter from this handler.</>
  • render(record, traceback, message_renderable) (ConsoleRenderable) Render log for display.</>
  • render_message(record, message) (ConsoleRenderable) Render message text in to Text.</>
  • setFormatter(fmt) Set the formatter for this handler.</>
  • setLevel(level) Set the logging level of this handler. level must be an int or a str.</>
method

addFilter(filter)

Add the specified filter to this handler.

method

removeFilter(filter)

Remove the specified filter from this handler.

method

filter(record)

Determine if a record is loggable by consulting all the filters.

The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero.

.. versionchanged:: 3.2

Allow filters to be just callables.

method

createLock()

Acquire a thread lock for serializing access to the underlying I/O.

method

acquire()

Acquire the I/O thread lock.

method

release()

Release the I/O thread lock.

method

setLevel(level)

Set the logging level of this handler. level must be an int or a str.

method

format(record)

Format the specified record.

If a formatter is set, use it. Otherwise, use the default formatter for the module.

method

handle(record)

Conditionally emit the specified logging record.

Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.

method

setFormatter(fmt)

Set the formatter for this handler.

method

flush()

Ensure all logging output has been flushed.

This version does nothing and is intended to be implemented by subclasses.

method

close()

Tidy up any resources used by the handler.

This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.

method

handleError(record)

Handle errors which occur during an emit() call.

This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method.

method

emit(record)

Invoked by logging.

method

render_message(record, message)

Render message text in to Text.

Parameters
  • record (LogRecord) logging Record.
  • message (str) String containing log message.
Returns (ConsoleRenderable)

Renderable to display log message.

method

render(record, traceback, message_renderable)

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.

method

get_level_text(record)

Get the level name from the record.

Parameters
  • record (LogRecord) LogRecord instance.
Returns (Text)

A tuple of the style and level name.