Backport Python 3.8+ typing utils & add issubtype & more

Overview

typing-utils

Backport Python3.8+ typing utils & issubtype & more

Downloads
Python 3.6 Python 3.7 Python 3.8 Python 3.9

Install

    pip install typing_utils

API

issubtype

Check that the left argument is a subtype of the right.

For unions, check if the type arguments of the left is a subset of the right. Also works for nested types including ForwardRefs.

Examples:

    from typing_utils import issubtype

    issubtype(typing.List, typing.Any) == True
    issubtype(list, list) == True
    issubtype(list, typing.List) == True
    issubtype(list, typing.Sequence) == True
    issubtype(typing.List[int], list) == True
    issubtype(typing.List[typing.List], list) == True
    issubtype(list, typing.List[int]) == False
    issubtype(list, typing.Union[typing.Tuple, typing.Set]) == False
    issubtype(typing.List[typing.List], typing.List[typing.Sequence]) == True
    JSON = typing.Union[
        int, float, bool, str, None, typing.Sequence["JSON"],
        typing.Mapping[str, "JSON"]
    ]
    issubtype(str, JSON, forward_refs={'JSON': JSON}) == True
    issubtype(typing.Dict[str, str], JSON, forward_refs={'JSON': JSON}) == True
    issubtype(typing.Dict[str, bytes], JSON, forward_refs={'JSON': JSON}) == False

get_origin

Get the unsubscripted version of a type.

This supports generic types, Callable, Tuple, Union, Literal, Final and ClassVar. Return None for unsupported types.

Examples:

    from typing_utils import get_origin

    get_origin(Literal[42]) is Literal
    get_origin(int) is None
    get_origin(ClassVar[int]) is ClassVar
    get_origin(Generic) is Generic
    get_origin(Generic[T]) is Generic
    get_origin(Union[T, int]) is Union
    get_origin(List[Tuple[T, T]][int]) == list

get_args

Get type arguments with all substitutions performed.

For unions, basic simplifications used by Union constructor are performed.

Examples:

    from typing_utils import get_args

    get_args(Dict[str, int]) == (str, int)
    get_args(int) == ()
    get_args(Union[int, Union[T, int], str][int]) == (int, str)
    get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
    get_args(Callable[[], T][int]) == ([], int)

get_type_hints

Return type hints for an object.

This is often the same as obj.annotations, but it handles forward references encoded as string literals, and if necessary adds Optional[t] if a default value equal to None is set.

The argument may be a module, class, method, or function. The annotations are returned as a dictionary. For classes, annotations include also inherited members.

TypeError is raised if the argument is not of a type that can contain annotations, and an empty dictionary is returned if no annotations are present.

BEWARE -- the behavior of globalns and localns is counterintuitive (unless you are familiar with how eval() and exec() work). The search order is locals first, then globals.

  • If no dict arguments are passed, an attempt is made to use the globals from obj (or the respective module's globals for classes), and these are also used as the locals. If the object does not appear to have globals, an empty dictionary is used.

  • If one dict argument is passed, it is used for both globals and locals.

  • If two dict arguments are passed, they specify globals and locals, respectively.

Comments
  • Add testing against Python 3.9

    Add testing against Python 3.9

    I'm trying this library on Python 3.9, and specifically interested in the issubtype() call - I haven't found a good alternative anywhere.

    It's failing on a call to issubclass() with typing.Optional - so I wanted to see if the tests would pass here on Python 3.9 before digging deeper.

    opened by miketheman 4
  • Couple of errors in overrides issues

    Couple of errors in overrides issues

    https://github.com/mkorpela/overrides/issues/78

    https://github.com/mkorpela/overrides/issues/79

    I think I need to insert this package code to overrides, if it seems there is no maintenance. Basically the issues are now in overrides production, so I need to fix them fast. I can move back to using this library if there is a fixing release (I can also make a PR for that).

    opened by mkorpela 2
  • The infamous TypeVar

    The infamous TypeVar

    Hi all, Nice lib :) We've been trying to get signature checking to overrides. TypeVar is making my head hurt. 😢 I wish it would work with issubtype but now getting results that kind of point that the method should give three possible results: Yes, No, Unknown..

    from typing_utils import issubtype
    from typing import TypeVar
    T = TypeVar("T")
    K = TypeVar("K")
    C = TypeVar("C", bound=str)
    issubtype(str, T) # -> throws error, I think it should be unknown
    issubtype(T, T) # -> True -> and ok
    issubtype(K, T) # -> False ... hmm, I think it should be unknown
    issubtype(T, int) # -> False ... hmm, I think it should be unknown
    issubtype(C, str) # -> False -> should in my opinion be True
    

    Sincerely, your biggest user https://pypistats.org/packages/typing-utils ;)

    opened by mkorpela 1
  • fix: list args of Callable

    fix: list args of Callable

    Changes: https://github.com/bojiang/typing_utils/pull/6/files#diff-556812789bdf8b0b5fa491afe93530be33abb8fd41150bec1da8da6b7c43e064R128 Context: fix #5

    opened by bojiang 0
  • Literal is broken

    Literal is broken

    After the recent pull request, issubtype produces incorrect results for Literals and exceptions when string literals are used.

    EDIT: apparently the incorrect behavior was there already before, but now instead of RecursionError there is another error

    opened by apirogov 2
Releases(v0.1.0)
A framework for detecting, highlighting and correcting grammatical errors on natural language text.

Gramformer Human and machine generated text often suffer from grammatical and/or typographical errors. It can be spelling, punctuation, grammatical or

Prithivida 1.3k Jan 08, 2023
flake8 plugin that integrates isort

Flake8 meet isort Use isort to check if the imports on your python files are sorted the way you expect. Add an .isort.cfg to define how you want your

Gil Forcada Codinachs 139 Nov 08, 2022
Run isort, pyupgrade, mypy, pylint, flake8, and more on Jupyter Notebooks

Run isort, pyupgrade, mypy, pylint, flake8, mdformat, black, blacken-docs, and more on Jupyter Notebooks ✅ handles IPython magics robustly ✅ respects

663 Jan 08, 2023
Rust like Option and Result types in Python

Option Rust-like Option and Result types in Python, slotted and fully typed. An Option type represents an optional value, every Option is either Some

45 Dec 13, 2022
Pylint plugin to enforce some secure coding standards for Python.

Pylint Secure Coding Standard Plugin pylint plugin that enforces some secure coding standards. Installation pip install pylint-secure-coding-standard

Nguyen Damien 2 Jan 04, 2022
Enforce the same configuration across multiple projects

Nitpick Flake8 plugin to enforce the same tool configuration (flake8, isort, mypy, Pylint...) across multiple Python projects. Useful if you maintain

Augusto W. Andreoli 315 Dec 25, 2022
A Pylint plugin to analyze Flask applications.

pylint-flask About pylint-flask is Pylint plugin for improving code analysis when editing code using Flask. Inspired by pylint-django. Problems pylint

Joe Schafer 62 Sep 18, 2022
Tool for pinpointing circular imports in Python. Find cyclic imports in any project

Pycycle: Find and fix circular imports in python projects Pycycle is an experimental project that aims to help python developers fix their circular de

Vadim Kravcenko 311 Dec 15, 2022
The strictest and most opinionated python linter ever!

wemake-python-styleguide Welcome to the strictest and most opinionated python linter ever. wemake-python-styleguide is actually a flake8 plugin with s

wemake.services 2.1k Jan 01, 2023
A python documentation linter which checks that the docstring description matches the definition.

Darglint A functional docstring linter which checks whether a docstring's description matches the actual function/method implementation. Darglint expe

Terrence Reilly 463 Dec 31, 2022
A simple plugin that allows running mypy from PyCharm and navigate between errors

mypy-PyCharm-plugin The plugin provides a simple terminal to run fast mypy daemon from PyCharm with a single click or hotkey and easily navigate throu

Dropbox 301 Dec 09, 2022
mypy plugin for loguru

loguru-mypy A fancy plugin to boost up your logging with loguru mypy compatibility logoru-mypy should be compatible with mypy=0.770. Currently there

Tomasz Trębski 13 Nov 02, 2022
The official GitHub mirror of https://gitlab.com/pycqa/flake8

Flake8 Flake8 is a wrapper around these tools: PyFlakes pycodestyle Ned Batchelder's McCabe script Flake8 runs all the tools by launching the single f

Python Code Quality Authority 2.6k Jan 03, 2023
Reference implementation of sentinels for the Python stdlib

Sentinels This is a reference implementation of a utility for the definition of sentinel values in Python. This also includes a draft PEP for the incl

Tal Einat 22 Aug 27, 2022
Design by contract for Python. Write bug-free code. Add a few decorators, get static analysis and tests for free.

A Python library for design by contract (DbC) and checking values, exceptions, and side-effects. In a nutshell, deal empowers you to write bug-free co

Life4 473 Dec 28, 2022
Mypy plugin and stubs for SQLAlchemy

Pythonista Stubs Stubs for the Pythonista iOS API. This allows for better error detection and IDE / editor autocomplete. Installation and Usage pip in

Dropbox 521 Dec 29, 2022
A plugin for Flake8 that provides specializations for type hinting stub files

flake8-pyi A plugin for Flake8 that provides specializations for type hinting stub files, especially interesting for linting typeshed. Functionality A

Łukasz Langa 58 Jan 04, 2023
A plugin for Flake8 that checks pandas code

pandas-vet pandas-vet is a plugin for flake8 that provides opinionated linting for pandas code. It began as a project during the PyCascades 2019 sprin

Jacob Deppen 146 Dec 28, 2022
Flake8 plugin to validate annotations complexity

flake8-annotations-complexity An extension for flake8 to report on too complex type annotations. Complex type annotations often means bad annotations

BestDoctor 41 Dec 28, 2022
Tools for improving Python imports

imptools Tools for improving Python imports. Installation pip3 install imptools Overview Detailed docs import_path Import a module from any path on th

Danijar Hafner 7 Aug 07, 2022