pytwd.quality package

Subpackages

Submodules

pytwd.quality.checksheet module

pytwd.quality.custom_warnings module

THIS MODULE IS DEPRECATED. USE QualityWarning LOGGING SYSTEM INSTEAD

This module sets up unique warnings and their codes used within the PyTWD pacakge.

exception DeprecationWarning(message)

Bases: PytwdWarning

code = 'D001'
exception DesignWarning(message)

Bases: QualityWarning

code = 'Q004'
exception ImATeapot(message)

Bases: UserWarning

code = 'H418'
exception PendingDeprecationWarning(message)

Bases: PytwdWarning

code = 'D002'
exception PytwdWarning(message)

Bases: Warning

exception QualityWarning(message)

Bases: PytwdWarning

code = 'Q001'
exception RedeclaredSymbolWarning(message)

Bases: QualityWarning

code = 'Q002'
exception SyntaxWarning(message)

Bases: PytwdWarning

code = 'S001'
exception TemplateCustomizationWarning(message)

Bases: QualityWarning

code = 'Q003'
exception UserWarning(message)

Bases: PytwdWarning

code = 'U001'
class WarningMessage(pytwd_code, message, module, class_name)

Bases: tuple

class_name

Alias for field number 3

message

Alias for field number 1

module

Alias for field number 2

pytwd_code

Alias for field number 0

custom_formatwarning(msg, *args, **kwargs)

pytwd.quality.errors module

This module comprises of all the unique PyTWD errors used within the package.

exception AssertionError

Bases: PytwdError

exception FileNotFoundError

Bases: PytwdError

exception IndexError

Bases: PytwdError

exception KeyError

Bases: PytwdError

exception NotImplementedError

Bases: PytwdError

exception PermissionError

Bases: PytwdError

exception PytwdError

Bases: Exception

exception SyntaxError

Bases: PytwdError

exception TypeError

Bases: PytwdError

exception ValueError

Bases: PytwdError

raise_on_double_spaces(filepath)

Raise if the name of a file contains two or more consecutive spaces.

Parameters:

filepath (Union[Path, str, FigureDef]) -- Passed filename

Raises:

PytwdError --

If the name of a file contains two or more consecutive spaces.

Examples:

>>> raise_on_double_spaces("valid_filename.txt")
>>> raise_on_double_spaces("some  filename.txt") 
Traceback (most recent call last):
errors.PytwdError: The following filename:"some>>>  <<<filename.txt" contains at least 2 consecutive spacings.
The arrows ">>>  <<<" indicate the location of the error. Please revise the filename to only one spacing between words or letters
raise_on_missing_file(filepath)

Raise if the given filepath does not exist or if the provided file suffix does not match the actual suffix of the file (also case sensitive). The latter is done to avoid unexpected errors on Linux-based systems when a notebook is developed on a Windows-based system.

Parameters:

filepath (Union[Path, str]) -- Passed filename

Raises:

FileNotFoundError -- If the file does not exist or if the file suffix case does not match

pytwd.quality.warning_logging module

class ConsoleFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)

Bases: Formatter

A custom logging formatter that formats QualityWarning messages for console output.

The ConsoleFormatter checks if the log record's message is an instance of QualityWarning and uses its to_console() method to format the message. If the message is not a QualityWarning, it falls back to the default formatting provided by the base logging.Formatter class.

Usage Example:

>>> logger = logging.getLogger(LOGGER_NAME)
>>> console_handler = logging.StreamHandler()
>>> console_handler.setFormatter(ConsoleFormatter())
>>> logger.addHandler(console_handler)
>>> warning = QualityWarning(
...     message="Console formatter test",
...     category=WarningCategory.ENGINEERING,
...     severity=WarningSeverity.WARNING
... )
>>> logger.warning(warning)
format(record)

Format the specified record as text.

The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

class JSONFileHandler(log_file)

Bases: Handler

A custom logging handler that saves QualityWarning messages to a JSON file.

The JSONFileHandler writes warnings to a specified JSON file, maintaining a list of all logged warnings. If the file already exists, it appends the new warning to the existing list; otherwise, it creates a new file. It ensures that the directory for the log file exists by creating it if necessary.

Parameters:

log_file -- The path to the JSON log file where warnings will be saved.

emit(record)

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

class JsonFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)

Bases: Formatter

A custom logging formatter that formats log records into JSON strings.

The JsonFormatter creates a JSON-formatted string containing the message, severity level, timestamp, and any additional metadata from the log record. This is useful for logging warnings and errors to a file in a structured format.

format(record)

Format the specified record as text.

The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

class NotebookDisplayHandler(level=0)

Bases: Handler

A custom logging handler that displays QualityWarning messages in Jupyter notebooks.

The NotebookDisplayHandler emits log records by formatting QualityWarning instances into HTML using their to_html() method and displays them using Jupyter's display function with Markdown rendering. If the message is not a QualityWarning, it converts it into one using its string representation.

Usage Example:

>>> logger = logging.getLogger(LOGGER_NAME)
>>> notebook_handler = NotebookDisplayHandler()
>>> logger.addHandler(notebook_handler)
>>> warning = QualityWarning(
...     message="Notebook handler test",
...     category=WarningCategory.ENGINEERING,
...     severity=WarningSeverity.INFO
... )
>>> logger.warning(warning)
<IPython.core.display.Markdown object>
emit(record)

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

class QualityWarning(message, category=WarningCategory.UNCATEGORIZED, subcategory=WarningSubCategory.UNCATEGORIZED, severity=WarningSeverity.WARNING, header='', solution='', **metadata)

Bases: object

Represents a custom quality warning with detailed information.

The QualityWarning class encapsulates warning details such as message, category, subcategory, severity, header, solution, and metadata. It captures caller information and normalizes inputs for consistency.

Parameters:
  • message (str) -- The main warning message.

  • category (Union[WarningCategory, str]) -- The category of the warning. Defaults to WarningCategory.UNCATEGORIZED.

  • subcategory (Union[WarningSubCategory, str, None]) -- The subcategory of the warning. Defaults to WarningSubCategory.UNCATEGORIZED.

  • severity (Union[WarningSeverity, str]) -- The severity level of the warning. Defaults to WarningSeverity.WARNING.

  • header (str) -- An optional header for the warning message.

  • solution (str) -- An optional suggested solution for the warning.

  • metadata -- Additional keyword arguments representing metadata, such as function name or filename.

Usage example:

>>> warning = QualityWarning(
...        message="This is a test warning.",
...        category=WarningCategory.ENGINEERING,
...        subcategory=WarningSubCategory.UNCATEGORIZED,
...        severity=WarningSeverity.CRITICAL,
...        header="Test Warning",
...        solution="Please check your configuration.",
...        extra_info="Additional details")
>>> print(warning.message)
This is a test warning.
>>> print(warning.category)
WarningCategory.ENGINEERING
>>> print(warning.severity)
WarningSeverity.CRITICAL
>>> warning = QualityWarning(message="This warning is for developers")
>>> print(warning.message)
This warning is for developers
to_console()

Convert the warning message to a string format for console output.

to_dict()

Return the warning as a dictionary for logging purposes.

to_html()

Convert the warning message to markdown format for display in Jupyter.

class WarningCategory(value)

Bases: Enum

An enumeration.

DEVELOPER = 4
ENGINEERING = 1
PROGRAMMING = 3
REPORTING = 2
UNCATEGORIZED = 5
class WarningCategoryFilter(exclude_categories=None)

Bases: Filter

A logging filter that excludes log records based on specified warning categories.

The WarningCategoryFilter can be added to a logger or handler to filter out QualityWarning messages that belong to certain categories.

Parameters:

exclude_categories -- A list of WarningCategory enums to exclude from logging. If None, no categories are excluded.

Usage Example:

>>> logger = logging.getLogger(LOGGER_NAME)
>>> category_filter = WarningCategoryFilter(exclude_categories=[WarningCategory.DEVELOPER])
>>> logger.addFilter(category_filter)
>>> warning = QualityWarning(
...     message="This is a developer warning.",
...     category=WarningCategory.DEVELOPER,
... )
>>> logger.warning(warning)
>>> # Since the warning category is excluded, it should not appear in the logs
filter(record)

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.

class WarningSeverity(value)

Bases: Enum

An enumeration.

CRITICAL = 3
INFO = 1
WARNING = 2
class WarningSubCategory(value)

Bases: Enum

An enumeration.

DEPRECATION = 1
SKIP_QUALITY_SHEET = 4
TEMPLATE_CUSTOMIZED = 2
UNCATEGORIZED = 3
configure_logger(logger, log_file=None, show_developer_warnings=False)

Configure the given logger with appropriate handlers and formatters.

This function sets up the provided logger by adding handlers for notebook display, console output, and JSON file logging. It applies filters to exclude developer warnings in notebook output if specified.

The notebook display is only used when in JupyterHub. The console output is used otherwise, and the JSON file logging is only used if a log_file path is provided.

Parameters:
  • logger (Logger) -- The logger instance to configure.

  • log_file (Union[str, Path, None]) -- The path to the log file for JSON logging. If None, JSON logging is not configured.

  • show_developer_warnings (bool) -- If False, developer warnings are excluded from notebook output.

Usage example:

>>> logger = logging.getLogger(LOGGER_NAME)
>>> configure_logger(logger, show_developer_warnings=False)
<Logger quality_logger (WARNING)>
>>> warning = QualityWarning(
...        message="This is a test warning.",
...        category=WarningCategory.ENGINEERING,
...        subcategory=WarningSubCategory.UNCATEGORIZED,
...        severity=WarningSeverity.CRITICAL,
...        header="Test Warning",
...        solution="Please check your configuration.",
...        extra_info="Additional details")
>>> logger.warning(warning)
suppress_logging(logger, level=50)

Temporarily suppress logging messages of a logger below the specified level.

Parameters:
  • logger -- The logger to adjust.

  • level -- The logging level to set temporarily (default: logging.CRITICAL).

Module contents