Warning

Most of the documentation was written prior to version 0.5 and needs to be updated. This work has now started for version 0.7 and we aim to have it completed before version 0.8 is available.

Public API

The following Public API has been generated automatically by Sphinx last time the documentation was updated.

friendly_traceback

With the exceptions of the functions that are specific to the console, this module contains all the functions that are part of the public API. While Friendly-traceback is still considered to be in beta stage, we do attempt to avoid creating incompatibility for the functions here when introducing changes.

The goal is to be even more careful to avoid introducing incompatibilities when reaching beta stage, and planning to be always backward compatible starting at version 1.0 – except possibly for the required minimal Python version.

Friendly-traceback is currently compatible with Python versions 3.6 or newer.

If you find that some additional functionality would be useful to have as part of the public API, please let us know.

enable_warnings(testing=False)[source]

Used to enable all warnings, with ‘always’ being used as the parameter for warnings.simplefilter.

While friendly_traceback, used by many third-party packages, does not automatically handle warnings by default, friendly, which is meant to be used by end-users instead of other packages/libraries, does call enable_warnings by default.

Return type

None

friendly_exec(source, globals_=None, locals_=None)[source]

A version of exec that uses a different filename each time instead of the Python default ‘<string>’, and caches the source. This makes it possible to provide more help on code executed via ‘exec’.

Return type

None

add_ignored_warnings(do_not_show_warning)[source]

Adds a function which will be passed warning_instance, warning_type, filename, lineno as arguments when a warning is raised. If this function returns True, the warning will be ignored.

This is intended for third-party packages that might trigger warnings which should not be shown to a user of friendly_traceback.

Return type

None

add_other_attribute_names(attributes)[source]

Intended for extension to friendly_traceback that provide support for some other modules. An example is friendly_pandas. These names can be used as suggestion in case of a NameError, suggesting that a given module (name) should perhaps be imported.

Parameters

attributes (Dict) –

A dict with attribute names used as keys and a sequence of modules containing such attributes. An example from the standard library might be:

attributes = {"cos": ["cmath", "math"],
              "sin": ["cmath", "math"] }

Return type

None

add_other_module_names_synonyms(synonyms)[source]

Intended for extension to friendly_traceback that provide support for some other modules. An example is friendly_pandas. These names can be used as suggestion in case of a NameError, suggesting that a given module (name) should perhaps be imported. For example, given names = {"np": "numpy"}, if np is an unknown name, the suggestion would include import numpy as np

Parameters

synonyms (Dict) – a dict containing synonyms often used for module names imported. For example: synonyms = {"np": "numpy"}

Return type

None

add_other_set_lang(func)[source]

Intended for extension to friendly_traceback that can also do translations.

Parameters

func (Callable[[str], None]) – a callable that should be invoked when set_lang is called to also set the language of the extension.

Return type

None

exclude_directory_from_traceback(dir_name)[source]

Exclude all files found in a given directory, including subdirectories, from appearing in a traceback generated by Friendly. Note that this does not apply to the true Python traceback obtained using "debug_tb".

Parameters

dir_name (Union[str, PathLike]) – the path representing the directory to exclude.

Return type

None

exclude_file_from_traceback(full_path)[source]

Exclude a file from appearing in a traceback generated by Friendly. Note that this does not apply to the true Python traceback obtained using "debug_tb" in interactive mode.

Parameters

full_path (Union[str, PathLike]) – the path of the file to exclude from the traceback.

Return type

None

explain_traceback(redirect=None)[source]

Replaces a standard traceback by a friendlier one, giving more information about a given exception than a standard traceback. Note that this excludes SystemExit and KeyboardInterrupt which are re-raised.

Parameters

redirect (Union[str, Callable[[str], None], None]) – some specified stream. By default, the output goes to sys.stderr. If the string "capture" is given as the value for redirect, the output is saved and can be later retrieved by get_output().

Return type

None

get_include()[source]

Retrieves the single string value used to determine what to include in the traceback. See set_include() for details.

Return type

Literal[‘message’, ‘hint’, ‘what’, ‘why’, ‘where’, ‘friendly_tb’, ‘python_tb’, ‘debug_tb’, ‘explain’, ‘no_tb’]

get_lang()[source]

Returns the current language that had been set for translations.

Note that the value returned may not reflect truly what is being seen by the end user: if the translations do not exist for that language, the default English strings are used.

Return type

str

get_output(flush=True)[source]

Returns the result of captured output as a string which can be written anywhere desired.

Parameters

flush (bool) – True y default, flushes all the captured content.

Return type

str

get_stream()[source]

Returns the value of the current stream used for output.

Return type

Callable[[str], None]

hide_secrets(patterns=None)[source]

Intended to prevent values of certain variables to be shown.

Parameters

patterns (Optional[List[str]]) – a list of regular expression patterns.

Return type

None

install(lang=None, redirect=None, include='explain', _debug=False)[source]

Replaces sys.excepthook by friendly’s own version. Intercepts, and can provide an explanation for all Python exceptions except for SystemExist and KeyboardInterrupt.

Parameters
  • lang (Optional[str]) – language to be used for translations. If not available, English will be used as a default.

  • redirect (Union[str, Callable[[str], None], None]) – stream to be used to send the output. The default is sys.stderr.

  • include (Literal[‘message’, ‘hint’, ‘what’, ‘why’, ‘where’, ‘friendly_tb’, ‘python_tb’, ‘debug_tb’, ‘explain’, ‘no_tb’]) – controls the amount of information displayed. See set_include() for details.

  • _debug (Optional[bool]) – optional argument that can be used to enable some debugging features.

Return type

None

is_installed()[source]

Returns True if friendly_traceback is installed, False otherwise.

Return type

bool

run(filename, lang='en', include=None, args=None, console=True, formatter='repl', redirect=None, ipython_prompt=True)[source]

Given a filename (relative or absolute path) ending with the “.py” extension, this function executes the code in the file.

If console is set to False, run() returns an empty dict if a SyntaxError was raised, otherwise returns the dict in which the module (filename) was executed.

If console is set to True (the default), the execution continues as an interactive session in a Friendly console, with the module dict being used as the locals() dict.

Parameters
  • lang (str) – language used; currently ‘en’ (default), ‘fr’, ‘es’, ‘ta’, ‘ru’, ‘it’, ‘he’ are available.

  • include (Optional[Literal[‘message’, ‘hint’, ‘what’, ‘why’, ‘where’, ‘friendly_tb’, ‘python_tb’, ‘debug_tb’, ‘explain’, ‘no_tb’]]) – specifies what information is to be included if an exception is raised; the default is “friendly_tb” if console is set to True, otherwise it is “explain”

  • args (Optional[Sequence[str]]) –

    strings tuple that is passed to the program as though it was run on the command line as follows:

    python filename.py arg1 arg2 ...
    

Return type

Optional[Dict[str, Any]]

set_formatter(formatter=None)[source]

Sets the default formatter. If no argument is given, the default formatter is used.

Return type

None

set_include(include)[source]

Specifies the information to include in the traceback.

Parameters

include (Literal[‘message’, ‘hint’, ‘what’, ‘why’, ‘where’, ‘friendly_tb’, ‘python_tb’, ‘debug_tb’, ‘explain’, ‘no_tb’]) – one of the following allowed values: message, message_plus, hint, what, why, where, friendly_tb, python_tb, debug_tb, detailed_tb, explain, no_tb

Return type

None

set_lang(lang='en')[source]

Sets the language to be used for the display.

Parameters

lang (str) – If no translations exist for that language, the original English strings will be used. If a value of None is used, a list of available languages is returned.

Return type

Optional[List[str]]

set_stream(redirect=None)[source]

Sets the stream to which the output should be directed.

Parameters

redirect (Union[str, Callable[[str], None], None]) – if the string "capture" is given as argument, the output is saved and can be later retrieved by get_output(). If no argument is given, the default stream (stderr) is set.

Return type

None

start_console(local_vars=None, formatter=None, include='friendly_tb', lang='en', banner=None, displayhook=None, ipython_prompt=True)[source]

Starts a Friendly console.

Return type

None

test_secrets(name='')[source]

Given a variable name that exists in the local scope where this function is invoked returns the value that will be shown if the variable value needs to be shown in a traceback.

Return type

Optional[str]

uninstall()[source]

Resets sys.excepthook to Python’s default.

Return type

None

friendly_traceback.info_generic

This module contains the necessary class and functions needed to help describing what a given exception or warning means (i.e. the answer to why()) of an exception. Most of the content should be considered to be private.

It does contain one decorator (register) which is intended to be part of the public API, but needs to be imported from this module instead of simply from friendly_traceback.

@register(error_class)[source]

Decorator used to record as available an explanation for a given exception.

Parameters

error_class (Type[BaseException]) – an exception class.

Usage:

from friendly_traceback.info_generic import register

@register
def describe(SomeErrorOrWarning) -> str:
    '''`SomeErrorOrWarning` means that ...'''
Return type

Callable[[Callable[[], str]], Callable[[], str]]

friendly_traceback.message_parser

This module contains the necessary class and functions needed to help finding the cause (specific information aka answer to why()) of an exception. Most of the content should be considered to be private.

It does contain one function (get_parser) which is intended to be part of the public API, but needs to be imported from this module instead of simply from friendly_traceback.

get_parser(exception_type)[source]

Gets a ‘parser’ to find the cause for a given exception.

Parameters

exception_type (Type[TypeVar(_E, bound= BaseException)]) – an exception class.

Usage:

parser = get_parser(SomeSpecificError)

@parser.add
def some_meaningful_name(message: str,
                         tb_data: TracebackData) -> dict:
    if not handled_by_this_function(message):
        return {}  # let other parsers deal with it

    ...
Return type

RuntimeMessageParser

friendly_traceback.about_warnings

This module includes all relevant classes and functions so that friendly-traceback can give help with warnings.

It contains one function (enable_warnings) which is part of the API, and one (get_warning_parser) which is the only other function in this module which is intended to be part of the public API. However, while the latter can be imported using from friendly_traceback import enable_warnings, get_warning_parser needs to be imported from this module.

get_warning_parser(warning_type)[source]

Gets a ‘parser’ to find the cause for a given warning.

Parameters

warning_type (Type[TypeVar(_E, bound= BaseException)]) – a warning class.

Usage:

parser = get_warning_parser(SomeSpecificWarning)

@parser.add
def some_meaningful_name(warning_message: str,
                         warning_data: WarningDataParser) -> dict:
    if not handled_by_this_function(warning_message):
        return {}  # let other parsers deal with it

    ...
Return type

WarningDataParser