Skip to main content

Functionality for types

Project description

image Downloads Pypi version codecov Scrutinizer Code Quality

Typish

  • Functions for thorough checks on types
  • Instance checks considering generics
  • Typesafe Duck-typing

Example

>>> from typing import Iterable
>>> from typish import instance_of
>>> instance_of([1, 2, 3], Iterable[int])
True

Installation

pip install typish

Content

Functions

Function Description
subclass_of(cls: type, *args: type) -> bool Returns whether cls is a sub type of all types in args
instance_of(obj: object, *args: type) -> bool Returns whether cls is an instance of all types in args
get_origin(t: type) -> type Return the "origin" of a generic type. E.g. get_origin(List[str]) gives list.
get_args(t: type) -> typing.Tuple[type, ...] Return the arguments of a generic type. E.g. get_args(List[str]) gives (str, ).
get_alias(cls: T) -> typing.Optional[T] Return the typing alias for a type. E.g get_alias(list) gives List.
get_type(inst: T, use_union: bool = False) -> typing.Type[T] Return the (generic) type of an instance. E.g. a list of ints will give List[int].
common_ancestor(*args: object) -> type Return the closest common ancestor of the given instances.
common_ancestor_of_types(*args: type) -> type Return the closest common ancestor of the given classes.
get_args_and_return_type(hint: typing.Type[typing.Callable]) -> typing.Tuple[typing.Optional[typing.Tuple[type]], typing.Optional[type]] Get the argument types and the return type of a callable type hint (e.g. Callable[[int], str]).
get_type_hints_of_callable(func: typing.Callable) -> typing.Dict[str, type] Return the type hints of the parameters of the given callable.
is_type_annotation(item: typing.Any) -> bool Returns whether item is a type or a typing type.

Types

Type Description
T A generic Type var.
KT A Type var for keys in a dict.
VT A type var for values in a dict.
Empty The type of emptiness (= Parameter.empty).
Unknown The type of something unknown.
Module The type of a module.
NoneType The type of None.
EllipsisType The type of ....

Classes

SubscriptableType

This metaclass allows a type to become subscriptable.

Example:

class MyClass(metaclass=SubscriptableType):
    ...

Now you can do:

MyClass2 = MyClass['some args']
print(MyClass2.__args__)
print(MyClass2.__origin__)

Output:

some args
<class '__main__.MyClass'>

Something

Define an interface with typish.Something.

Example:

Duck = Something['walk': Callable[[], None], 
                 'quack': Callable[[], None]]

Anything that has the attributes defined in Something with the right type is considered an instance of that Something (classes, objects, even modules...).

The builtin isinstance is supported as well as typish.instance_of.

ClsDict

A dictionary that uses instance checking to determine which value to return. It only accepts types as keys.

This is particularly useful when a function accepts multiple types for an argument and you want to split the implementation into separate functions.

Example:

def _handle_str(item):
    ...

def _handle_int(item):
    ...

def func(item):
    # Suppose item can be a string or an int, you can use ClsDict to
    # pick a handler function.

    cd = ClsDict({
        str: _handle_str,
        int: _handle_int,
    })

    handler = cd[item]  # Pick the right handler.
    handler(item)       # Call that handler.

ClsFunction

A callable that uses ClsDict to call the right function. Below is the same example as above, but slightly modified in that it uses ClsFunction.

Example:

def _handle_str(item):
    ...


def _handle_int(item):
    ...


def func(item):
    # Suppose item can be a string or an int, you can use ClsFunction to
    # delegate to the right handler function.

    function = ClsFunction({
        str: _handle_str,
        int: _handle_int,
    })

    function(item)

Literal

A backwards compatible variant of typing.Literal (Python3.8). When importing Literal from typish, you will get the typing.Literal if it is available.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

typish-1.6.0-py3-none-any.whl (27.7 kB view details)

Uploaded Python 3

File details

Details for the file typish-1.6.0-py3-none-any.whl.

File metadata

  • Download URL: typish-1.6.0-py3-none-any.whl
  • Upload date:
  • Size: 27.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.3

File hashes

Hashes for typish-1.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 13f7d5f1b86faab11f016af6d82a157b12dba60a82f2e823608a3ee8165eac28
MD5 326f486d00d42ba2d146d52b89d2a1ed
BLAKE2b-256 afb5b5ddbd624e12b40742a0bca7cd86db42f1b4f21f6503f74542ae046c3188

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page