Skip to main content

A collection of extra types and features for mypy

Project description

mypy-extras

wemake.services test codecov Python Version wemake-python-styleguide

Features

  • Provides a custom mypy plugin to enhance its possibilities
  • Provides new types that can be used in your programs with our plugin
  • Fully typed with annotations and checked with mypy, PEP561 compatible

Installation

pip install mypy-extras

You also need to configure mypy correctly and install our custom plugin:

# In setup.cfg or mypy.ini:
[mypy]
plugins =
  mypy_extras.plugin.entrypoint

We also recommend to use the same mypy settings we use.

Usage

AttrOf

We provide a special type to get named attributes of other types, like so:

from typing_extensions import Literal  # or typing on python3.8+
from mypy_extras import AttrOf

class User(object):
    def auth(self, username: str, password: str) -> bool:
        return False  # Just an example

def get_callback(user: User) -> AttrOf[User, Literal['auth']]:
    return user.auth

user: User
reveal_type(get_callback(user))
# Revealed type is 'def (username: builtins.str, password: builtins.str) -> builtins.bool'

ensure_attr

We can ensure that some str attribute exists on a object:

from mypy_extras import ensure_attr


class User(object):
    policy = 'update'


reveal_type(ensure_attr(User, 'policy'))  # Revealed type is 'Literal['policy']'
reveal_type(ensure_attr(User, 'missing'))  # Error: attribute "missing" does not exist on type "User"

It is useful when we do any manipulations with objects based on a string field:

DEFAULT_POLICY_FIELD: Final = ensure_attr(User, 'policy')  # typesafe
# vs
DEFAULT_POLICY_FIELD: Final = 'policy'  
# User can rename the field, and this will blow now!

License

MIT

Project details


Download files

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

Source Distribution

mypy-extras-0.1.0.tar.gz (7.7 kB view hashes)

Uploaded Source

Built Distribution

mypy_extras-0.1.0-py3-none-any.whl (8.5 kB view hashes)

Uploaded Python 3

Supported by

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