module documentation

Utility functions with no non-trivial dependencies.

Class FancyFormatter Apply color and bold font to terminal output.
Class IdMapper Generate integer ids for objects.
Exception DecodeError Exception raised when a file cannot be decoded due to an unknown encoding type.
Function bytes_to_human_readable_repr Converts bytes into some human-readable representation. Unprintable bytes such as the nul byte are escaped. For example:
Function check_python_version Report issues with the Python used to run mypy, dmypy, or stubgen
Function correct_relative_import Undocumented
Function count_stats Count total number of errors, notes and error_files in message list.
Function decode_python_encoding Read the Python file with while obeying PEP-263 encoding detection.
Function find_python_encoding PEP-263 for detecting Python file encoding
Function get_class_descriptors Undocumented
Function get_mypy_comments Undocumented
Function get_prefix Drop the final component of a qualified name (e.g. ('x.y' -> 'x').
Function get_terminal_width Get current terminal width if possible, otherwise return the default one.
Function get_top_two_prefixes Return one and two component prefixes of a fully qualified name.
Function get_unique_redefinition_name Get a simple redefinition name not present among existing.
Function hard_exit Kill the current process without fully cleaning up.
Function hash_digest Compute a hash digest of some data.
Function is_dunder Returns whether name is a dunder name.
Function is_stub_package_file Undocumented
Function is_sub_path Given two paths, return if path1 is a sub-path of path2.
Function is_sunder Undocumented
Function is_typeshed_file Undocumented
Function module_prefix Undocumented
Function parse_gray_color Reproduce a gray color in ANSI escape sequence
Function plural_s Undocumented
Function read_py_file Try reading a Python file as list of source lines.
Function replace_object_state Copy state of old node to the new node.
Function short_type Return the last component of the type name of an object.
Function should_force_color Undocumented
Function soft_wrap Wrap a long error message into few lines.
Function split_module_names Return the module and all parent module names.
Function split_target Undocumented
Function split_words Split line of text into words (but not within quoted groups).
Function time_spent_us Undocumented
Function trim_source_line Trim a line of source code to fit into max_len.
Function unmangle Remove internal suffixes from a short name.
Function unnamed_function Undocumented
Function write_junit_xml Undocumented
Constant CURSES_ENABLED Undocumented
Constant DEFAULT_COLUMNS Undocumented
Constant DEFAULT_SOURCE_OFFSET Undocumented
Constant ENCODING_RE Undocumented
Constant ERROR_TEMPLATE Undocumented
Constant FAIL_TEMPLATE Undocumented
Constant fields_cache Undocumented
Constant MINIMUM_WIDTH Undocumented
Constant MINIMUM_WINDOWS_BUILD_VT100 Undocumented
Constant MINIMUM_WINDOWS_MAJOR_VT100 Undocumented
Constant PASS_TEMPLATE Undocumented
Constant SPECIAL_DUNDERS Undocumented
Constant TYPESHED_DIR Undocumented
Type Variable T Undocumented
def bytes_to_human_readable_repr(b: bytes) -> str: (source)

Converts bytes into some human-readable representation. Unprintable bytes such as the nul byte are escaped. For example: >>> b = bytes([102, 111, 111, 10, 0]) >>> s = bytes_to_human_readable_repr(b) >>> print(s) foo >>> print(repr(s)) 'foo\n\x00'

def check_python_version(program: str): (source)

Report issues with the Python used to run mypy, dmypy, or stubgen

def correct_relative_import(cur_mod_id: str, relative: int, target: str, is_cur_package_init_file: bool) -> tuple[str, bool]: (source)

Undocumented

def count_stats(messages: list[str]) -> tuple[int, int, int]: (source)

Count total number of errors, notes and error_files in message list.

def decode_python_encoding(source: bytes) -> str: (source)

Read the Python file with while obeying PEP-263 encoding detection. Returns the source as a string.

def find_python_encoding(text: bytes) -> tuple[str, int]: (source)

PEP-263 for detecting Python file encoding

def get_class_descriptors(cls: type[object]) -> Sequence[str]: (source)

Undocumented

def get_mypy_comments(source: str) -> list[tuple[int, str]]: (source)

Undocumented

def get_prefix(fullname: str) -> str: (source)

Drop the final component of a qualified name (e.g. ('x.y' -> 'x').

def get_terminal_width() -> int: (source)

Get current terminal width if possible, otherwise return the default one.

def get_top_two_prefixes(fullname: str) -> tuple[str, str]: (source)

Return one and two component prefixes of a fully qualified name. Given 'a.b.c.d', return ('a', 'a.b'). If fullname has only one component, return (fullname, fullname).

def get_unique_redefinition_name(name: str, existing: Container[str]) -> str: (source)

Get a simple redefinition name not present among existing. For example, for name 'foo' we try 'foo-redefinition', 'foo-redefinition2', 'foo-redefinition3', etc. until we find one that is not in existing.

def hard_exit(status: int = 0): (source)

Kill the current process without fully cleaning up. This can be quite a bit faster than a normal exit() since objects are not freed.

def hash_digest(data: bytes) -> str: (source)

Compute a hash digest of some data. We use a cryptographic hash because we want a low probability of accidental collision, but we don't really care about any of the cryptographic properties.

def is_dunder(name: str, exclude_special: bool = False) -> bool: (source)

Returns whether name is a dunder name. Args: exclude_special: Whether to return False for a couple special dunder methods.

def is_stub_package_file(file: str) -> bool: (source)

Undocumented

def is_sub_path(path1: str, path2: str) -> bool: (source)

Given two paths, return if path1 is a sub-path of path2.

def is_sunder(name: str) -> bool: (source)

Undocumented

def is_typeshed_file(typeshed_dir: str|None, file: str) -> bool: (source)

Undocumented

def module_prefix(modules: Iterable[str], target: str) -> str|None: (source)

Undocumented

def parse_gray_color(cup: bytes) -> str: (source)

Reproduce a gray color in ANSI escape sequence

def plural_s(s: int|Sized) -> str: (source)

Undocumented

def read_py_file(path: str, read: Callable[[str], bytes]) -> list[str]|None: (source)

Try reading a Python file as list of source lines. Return None if something goes wrong.

def replace_object_state(new: object, old: object, copy_dict: bool = False, skip_slots: tuple[str, ...] = ()): (source)

Copy state of old node to the new node. This handles cases where there is __dict__ and/or attribute descriptors (either from slots or because the type is defined in a C extension module). Assume that both objects have the same __class__.

def short_type(obj: object) -> str: (source)

Return the last component of the type name of an object. If obj is None, return 'nil'. For example, if obj is 1, return 'int'.

def should_force_color() -> bool: (source)

Undocumented

def soft_wrap(msg: str, max_len: int, first_offset: int, num_indent: int = 0) -> str: (source)

Wrap a long error message into few lines. Breaks will only happen between words, and never inside a quoted group (to avoid breaking types such as "Union[int, str]"). The 'first_offset' is the width before the start of first line. Pad every next line with 'num_indent' spaces. Every line will be at most 'max_len' characters, except if it is a single word or quoted group. For example: first_offset ------------------------ path/to/file: error: 58: Some very long error message that needs to be split in separate lines. "Long[Type, Names]" are never split. ^^^^-------------------------------------------------- num_indent max_len

def split_module_names(mod_name: str) -> list[str]: (source)

Return the module and all parent module names. So, if `mod_name` is 'a.b.c', this function will return ['a.b.c', 'a.b', and 'a'].

def split_target(modules: Iterable[str], target: str) -> tuple[str, str]|None: (source)

Undocumented

def split_words(msg: str) -> list[str]: (source)

Split line of text into words (but not within quoted groups).

def time_spent_us(t0: int) -> int: (source)

Undocumented

def trim_source_line(line: str, max_len: int, col: int, min_width: int) -> tuple[str, int]: (source)

Trim a line of source code to fit into max_len. Show 'min_width' characters on each side of 'col' (an error location). If either start or end is trimmed, this is indicated by adding '...' there. A typical result looks like this: ...some_variable = function_to_call(one_arg, other_arg) or... Return the trimmed string and the column offset to to adjust error location.

def unmangle(name: str) -> str: (source)

Remove internal suffixes from a short name.

def unnamed_function(name: str|None) -> bool: (source)

Undocumented

def write_junit_xml(dt: float, serious: bool, messages: list[str], path: str, version: str, platform: str): (source)

Undocumented

CURSES_ENABLED: bool = (source)

Undocumented

Value
True
DEFAULT_COLUMNS: int = (source)

Undocumented

Value
80
DEFAULT_SOURCE_OFFSET: int = (source)

Undocumented

Value
4
ENCODING_RE = (source)

Undocumented

Value
re.compile(rb'([ \t\v]*#.*(\r\n?|\n))??[ \t\v]*#.*coding[:=][ \t]*([-\w\.]+)')
ERROR_TEMPLATE: str = (source)

Undocumented

Value
'''<?xml version="1.0" encoding="utf-8"?>
<testsuite errors="1" failures="0" name="mypy" skips="0" tests="1" time="{time:.
3f}">
  <testcase classname="mypy" file="mypy" line="1" name="mypy-py{ver}-{platform}"
 time="{time:.3f}">
    <error message="mypy produced errors">{text}</error>
  </testcase>
...
FAIL_TEMPLATE: str = (source)

Undocumented

Value
'''<?xml version="1.0" encoding="utf-8"?>
<testsuite errors="0" failures="1" name="mypy" skips="0" tests="1" time="{time:.
3f}">
  <testcase classname="mypy" file="mypy" line="1" name="mypy-py{ver}-{platform}"
 time="{time:.3f}">
    <failure message="mypy produced messages">{text}</failure>
  </testcase>
...
fields_cache: dict[type[object], list[str]] = (source)

Undocumented

Value
{}
MINIMUM_WIDTH: int = (source)

Undocumented

Value
20
MINIMUM_WINDOWS_BUILD_VT100: int = (source)

Undocumented

Value
10586
MINIMUM_WINDOWS_MAJOR_VT100: int = (source)

Undocumented

Value
10
PASS_TEMPLATE: str = (source)

Undocumented

Value
'''<?xml version="1.0" encoding="utf-8"?>
<testsuite errors="0" failures="0" name="mypy" skips="0" tests="1" time="{time:.
3f}">
  <testcase classname="mypy" file="mypy" line="1" name="mypy-py{ver}-{platform}"
 time="{time:.3f}">
  </testcase>
</testsuite>
...
SPECIAL_DUNDERS = (source)

Undocumented

Value
frozenset(('__init__',
           '__new__',
           '__call__',
           '__init_subclass__',
           '__class_getitem__'))
TYPESHED_DIR = (source)

Undocumented

Value
str(importlib_resources.files('mypy')/'typeshed')

Undocumented

Value
TypeVar('T')