typish


Nametypish JSON
Version 1.9.3 PyPI version JSON
download
home_pagehttps://github.com/ramonhagenaars/typish
SummaryFunctionality for types
upload_time2021-08-05 20:36:28
maintainer
docs_urlNone
authorRamon Hagenaars
requires_python
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            [![image](https://img.shields.io/pypi/pyversions/typish.svg)](https://pypi.org/project/typish/)
[![Downloads](https://pepy.tech/badge/typish)](https://pepy.tech/project/typish)
[![Pypi version](https://badge.fury.io/py/typish.svg)](https://badge.fury.io/py/typish)
[![codecov](https://codecov.io/gh/ramonhagenaars/typish/branch/master/graph/badge.svg)](https://codecov.io/gh/ramonhagenaars/typish)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/ramonhagenaars/typish/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/ramonhagenaars/typish/?branch=master)

# Typish

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

## Example

```python
>>> 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.
| ``is_from_typing(cls: type) -> bool`` | Returns whether ``cls`` is from the ``typing`` module.
| ``is_optional_type(cls: type) -> bool`` | Returns whether ``cls`` is considered to be an optional type.
| ``get_mro(obj: typing.Any) -> typing.Tuple[type, ...]`` | Wrapper around ``getmro`` from ``inspect`` to also support ``typing`` types.


### 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 ``...``.

### Decorators

#### hintable
This decorator allows one to capture the type hint of a variable that calls a function. If no hint is provided, `None` 
is passed as a value for `hint`.

Just remember: with great power comes great responsibility. Use this functionality wisely. You may want to make sure 
that if you hinted a variable with a certain type, your `hintable` function does indeed return a value of that type.

```python
@hintable
def cast(arg: Any, hint: Type[T]) -> T:
    return hint(arg)

# The type hint on x is passed to cast:
x: int = cast('42')

# It works with MyPy hints as well:
y = cast('42')  # type: int

# Not something you would normally do, but the type hint takes precedence:
z: int = cast('42')  # type: str
```

### Classes

#### SubscriptableType
This metaclass allows a type to become subscriptable.

*Example:*
```python
class MyClass(metaclass=SubscriptableType):
    ...
```
Now you can do:
```python
MyClass2 = MyClass['some args']
print(MyClass2.__args__)
print(MyClass2.__origin__)
```
Output:
```
some args
<class '__main__.MyClass'>
```

#### Something
Define an interface with ``typish.Something``.

*Example:*
```python
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:* 
```python

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:*

```python
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.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/ramonhagenaars/typish",
    "name": "typish",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Ramon Hagenaars",
    "author_email": "ramon.hagenaars@gmail.com",
    "download_url": "",
    "platform": "",
    "description": "[![image](https://img.shields.io/pypi/pyversions/typish.svg)](https://pypi.org/project/typish/)\n[![Downloads](https://pepy.tech/badge/typish)](https://pepy.tech/project/typish)\n[![Pypi version](https://badge.fury.io/py/typish.svg)](https://badge.fury.io/py/typish)\n[![codecov](https://codecov.io/gh/ramonhagenaars/typish/branch/master/graph/badge.svg)](https://codecov.io/gh/ramonhagenaars/typish)\n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/ramonhagenaars/typish/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/ramonhagenaars/typish/?branch=master)\n\n# Typish\n\n* Functions for thorough checks on types\n* Instance checks considering generics\n* Typesafe Duck-typing\n\n## Example\n\n```python\n>>> from typing import Iterable\n>>> from typish import instance_of\n>>> instance_of([1, 2, 3], Iterable[int])\nTrue\n```\n\n## Installation\n\n```\npip install typish\n```\n\n## Content\n\n### Functions\n\n| Function | Description\n|---|---\n| ``subclass_of(cls: type, *args: type) -> bool`` | Returns whether ``cls`` is a sub type of *all* types in ``args``\n| ``instance_of(obj: object, *args: type) -> bool`` | Returns whether ``cls`` is an instance of *all* types in ``args``\n| ``get_origin(t: type) -> type`` | Return the \"origin\" of a generic type. E.g. ``get_origin(List[str])`` gives ``list``.\n| ``get_args(t: type) -> typing.Tuple[type, ...]`` | Return the arguments of a generic type. E.g. ``get_args(List[str])`` gives ``(str, )``.\n| ``get_alias(cls: T) -> typing.Optional[T]`` | Return the ``typing`` alias for a type. E.g ``get_alias(list)`` gives ``List``.\n| ``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]``.\n| ``common_ancestor(*args: object) -> type`` | Return the closest common ancestor of the given instances.\n| ``common_ancestor_of_types(*args: type) -> type`` | Return the closest common ancestor of the given classes.\n| ``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]``). \n| ``get_type_hints_of_callable(func: typing.Callable) -> typing.Dict[str, type]`` | Return the type hints of the parameters of the given callable.\n| ``is_type_annotation(item: typing.Any) -> bool`` | Returns whether ``item`` is a ``type`` or a ``typing`` type.\n| ``is_from_typing(cls: type) -> bool`` | Returns whether ``cls`` is from the ``typing`` module.\n| ``is_optional_type(cls: type) -> bool`` | Returns whether ``cls`` is considered to be an optional type.\n| ``get_mro(obj: typing.Any) -> typing.Tuple[type, ...]`` | Wrapper around ``getmro`` from ``inspect`` to also support ``typing`` types.\n\n\n### Types\n\n| Type | Description\n|---|---|\n| ``T`` | A generic Type var.\n| ``KT`` | A Type var for keys in a dict.\n| ``VT`` | A type var for values in a dict.\n| ``Empty`` | The type of emptiness (= ``Parameter.empty``).\n| ``Unknown`` | The type of something unknown.\n| ``Module`` | The type of a module.\n| ``NoneType`` | The type of ``None``.\n| ``EllipsisType`` | The type of ``...``.\n\n### Decorators\n\n#### hintable\nThis decorator allows one to capture the type hint of a variable that calls a function. If no hint is provided, `None` \nis passed as a value for `hint`.\n\nJust remember: with great power comes great responsibility. Use this functionality wisely. You may want to make sure \nthat if you hinted a variable with a certain type, your `hintable` function does indeed return a value of that type.\n\n```python\n@hintable\ndef cast(arg: Any, hint: Type[T]) -> T:\n    return hint(arg)\n\n# The type hint on x is passed to cast:\nx: int = cast('42')\n\n# It works with MyPy hints as well:\ny = cast('42')  # type: int\n\n# Not something you would normally do, but the type hint takes precedence:\nz: int = cast('42')  # type: str\n```\n\n### Classes\n\n#### SubscriptableType\nThis metaclass allows a type to become subscriptable.\n\n*Example:*\n```python\nclass MyClass(metaclass=SubscriptableType):\n    ...\n```\nNow you can do:\n```python\nMyClass2 = MyClass['some args']\nprint(MyClass2.__args__)\nprint(MyClass2.__origin__)\n```\nOutput:\n```\nsome args\n<class '__main__.MyClass'>\n```\n\n#### Something\nDefine an interface with ``typish.Something``.\n\n*Example:*\n```python\nDuck = Something['walk': Callable[[], None], \n                 'quack': Callable[[], None]]\n```\n\nAnything that has the attributes defined in ``Something`` with the right type is \nconsidered an instance of that ``Something`` (classes, objects, even modules...).\n\nThe builtin ``isinstance`` is supported as well as ``typish.instance_of``.\n\n#### ClsDict\nA dictionary that uses instance checking to determine which value to return.\nIt only accepts types as keys.\n\nThis is particularly useful when a function accepts multiple types for an \nargument and you want to split the implementation into separate functions.\n\n*Example:* \n```python\n\ndef _handle_str(item):\n    ...\n\ndef _handle_int(item):\n    ...\n\ndef func(item):\n    # Suppose item can be a string or an int, you can use ClsDict to\n    # pick a handler function.\n\n    cd = ClsDict({\n        str: _handle_str,\n        int: _handle_int,\n    })\n\n    handler = cd[item]  # Pick the right handler.\n    handler(item)       # Call that handler.\n```\n\n#### ClsFunction\nA callable that uses `ClsDict` to call the right function.\nBelow is the same example as above, but slightly modified in \nthat it uses `ClsFunction`.\n\n*Example:*\n\n```python\ndef _handle_str(item):\n    ...\n\n\ndef _handle_int(item):\n    ...\n\n\ndef func(item):\n    # Suppose item can be a string or an int, you can use ClsFunction to\n    # delegate to the right handler function.\n\n    function = ClsFunction({\n        str: _handle_str,\n        int: _handle_int,\n    })\n\n    function(item)\n\n```\n\n#### Literal\nA backwards compatible variant of typing.Literal (Python3.8). When importing \n`Literal` from `typish`, you will get the `typing.Literal` if it is available.\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Functionality for types",
    "version": "1.9.3",
    "project_urls": {
        "Homepage": "https://github.com/ramonhagenaars/typish"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9dd63f56c9c0c12adf61dfcf4ed5c8ffd2c431db8dd85592067a57e8e1968565",
                "md5": "ea0489e00f8f7a3bb8b2eb0eff6ebecf",
                "sha256": "03cfee5e6eb856dbf90244e18f4e4c41044c8790d5779f4e775f63f982e2f896"
            },
            "downloads": -1,
            "filename": "typish-1.9.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ea0489e00f8f7a3bb8b2eb0eff6ebecf",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 45063,
            "upload_time": "2021-08-05T20:36:28",
            "upload_time_iso_8601": "2021-08-05T20:36:28.702918Z",
            "url": "https://files.pythonhosted.org/packages/9d/d6/3f56c9c0c12adf61dfcf4ed5c8ffd2c431db8dd85592067a57e8e1968565/typish-1.9.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2021-08-05 20:36:28",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "ramonhagenaars",
    "github_project": "typish",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "typish"
}
        
Elapsed time: 0.13554s