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)
Type annotations builder for boto3 compatible with VSCode, PyCharm, Emacs, Sublime Text, pyright and mypy.

mypy_boto3_builder Type annotations builder for boto3-stubs project. Compatible with VSCode, PyCharm, Emacs, Sublime Text, mypy, pyright and other too

Vlad Emelianov 2 Dec 05, 2022
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
Utilities for pycharm code formatting (flake8 and black)

Pycharm External Tools Extentions to Pycharm code formatting tools. Currently supported are flake8 and black on a selected code block. Usage Flake8 [P

Haim Daniel 13 Nov 03, 2022
PEP-484 typing stubs for SQLAlchemy 1.4 and SQLAlchemy 2.0

SQLAlchemy 2 Stubs These are PEP-484 typing stubs for SQLAlchemy 1.4 and 2.0. They are released concurrently along with a Mypy extension which is desi

SQLAlchemy 139 Dec 30, 2022
It's not just a linter that annoys you!

README for Pylint - https://pylint.pycqa.org/ Professional support for pylint is available as part of the Tidelift Subscription. Tidelift gives softwa

Python Code Quality Authority 4.4k Jan 04, 2023
Code audit tool for python.

Pylama Code audit tool for Python and JavaScript. Pylama wraps these tools: pycodestyle (formerly pep8) © 2012-2013, Florent Xicluna; pydocstyle (form

Kirill Klenov 967 Jan 07, 2023
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
Static type checker for Python

Static type checker for Python Speed Pyright is a fast type checker meant for large Python source bases. It can run in a “watch” mode and performs fas

Microsoft 9.2k Jan 03, 2023
coala provides a unified command-line interface for linting and fixing all your code, regardless of the programming languages you use.

"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." ― John F. Woods coala provides a

coala development group 3.4k Dec 29, 2022
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
Pylint plugin for improving code analysis for when using Django

pylint-django About pylint-django is a Pylint plugin for improving code analysis when analysing code using Django. It is also used by the Prospector t

Python Code Quality Authority 544 Jan 06, 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
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
Simple Python style checker in one Python file

pycodestyle (formerly called pep8) - Python style guide checker pycodestyle is a tool to check your Python code against some of the style conventions

Python Code Quality Authority 4.7k Jan 01, 2023
open source tools to generate mypy stubs from protobufs

mypy-protobuf: Generate mypy stub files from protobuf specs We just released a new major release mypy-protobuf 2. on 02/02/2021! It includes some back

Dropbox 527 Jan 03, 2023
docstring style checker

pydocstyle - docstring style checker pydocstyle is a static analysis tool for checking compliance with Python docstring conventions. pydocstyle suppor

Python Code Quality Authority 982 Jan 03, 2023
A Python Parser

parso - A Python Parser Parso is a Python parser that supports error recovery and round-trip parsing for different Python versions (in multiple Python

Dave Halter 520 Dec 26, 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 to check the completeness of MANIFEST.in for Python packages

check-manifest Are you a Python developer? Have you uploaded packages to the Python Package Index? Have you accidentally uploaded broken packages with

Marius Gedminas 270 Dec 26, 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