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 plugin for flake8 integrating Mypy.

flake8-mypy NOTE: THIS PROJECT IS DEAD It was created in early 2017 when Mypy performance was often insufficient for in-editor linting. The Flake8 plu

Łukasz Langa 103 Jun 23, 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 flake8 plugin to help you write better list/set/dict comprehensions.

flake8-comprehensions A flake8 plugin that helps you write better list/set/dict comprehensions. Requirements Python 3.6 to 3.9 supported. Installation

Adam Johnson 398 Dec 23, 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
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
Utilities for refactoring imports in python-like syntax.

aspy.refactor_imports Utilities for refactoring imports in python-like syntax. Installation pip install aspy.refactor_imports Examples aspy.refactor_i

Anthony Sottile 20 Nov 01, 2022
mypy plugin to type check Kubernetes resources

kubernetes-typed mypy plugin to dynamically define types for Kubernetes objects. Features Type checking for Custom Resources Type checking forkubernet

Artem Yarmoliuk 16 Oct 10, 2022
👻 Phantom types for Python

phantom-types Phantom types for Python will help you make illegal states unrepresentable and avoid shotgun parsing by enabling you to practice "Parse,

Anton Agestam 118 Dec 22, 2022
Optional static typing for Python 3 and 2 (PEP 484)

Mypy: Optional Static Typing for Python Got a question? Join us on Gitter! We don't have a mailing list; but we are always happy to answer questions o

Python 14.4k Jan 08, 2023
Flake8 plugin that checks import order against various Python Style Guides

flake8-import-order A flake8 and Pylama plugin that checks the ordering of your imports. It does not check anything else about the imports. Merely tha

Python Code Quality Authority 270 Nov 24, 2022
Type stubs for the lxml package

lxml-stubs About This repository contains external type annotations (see PEP 484) for the lxml package. Installation To use these stubs with mypy, you

25 Dec 26, 2022
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
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
Pyright extension for coc.nvim

coc-pyright Pyright extension for coc.nvim Install :CocInstall coc-pyright Note: Pyright may not work as expected if can't detect project root correct

Heyward Fann 1.1k Jan 02, 2023
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
Plugin for mypy to support zope.interface

Plugin for mypy to support zope.interface The goal is to be able to make zope interfaces to be treated as types in mypy sense. Usage Install both mypy

Shoobx 36 Oct 29, 2022
Mypy stubs, i.e., type information, for numpy, pandas and matplotlib

Mypy type stubs for NumPy, pandas, and Matplotlib This is a PEP-561-compliant stub-only package which provides type information for matplotlib, numpy

Predictive Analytics Lab 194 Dec 19, 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
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
An open-source, mini imitation of GitHub Copilot for Emacs.

Second Mate An open-source, mini imitation of GitHub Copilot using EleutherAI GPT-Neo-2.7B (via Huggingface Model Hub) for Emacs. This is a much small

Sam Rawal 238 Dec 27, 2022