Skip to content

Latest commit

 

History

History
87 lines (56 loc) · 2.92 KB

README.md

File metadata and controls

87 lines (56 loc) · 2.92 KB

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