https://github.com/wemake-services/mypy-extras
A collection of extra types and features for mypy
https://github.com/wemake-services/mypy-extras
Last synced: 4 months ago
JSON representation
A collection of extra types and features for mypy
- Host: GitHub
- URL: https://github.com/wemake-services/mypy-extras
- Owner: wemake-services
- License: mit
- Created: 2020-10-31T10:50:14.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2025-05-02T02:34:55.000Z (5 months ago)
- Last Synced: 2025-06-03T09:46:12.955Z (4 months ago)
- Language: Python
- Size: 908 KB
- Stars: 34
- Watchers: 3
- Forks: 0
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
# mypy-extras
[](https://wemake.services)
[](https://github.com/wemake-services/mypy-extras/actions?query=workflow%3Atest)
[](https://codecov.io/gh/wemake-services/mypy-extras)
[](https://pypi.org/project/mypy-extras/)
[](https://github.com/wemake-services/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](https://www.python.org/dev/peps/pep-0561/)## Installation
```bash
pip install mypy-extras
```You also need to [configure](https://mypy.readthedocs.io/en/stable/config_file.html)
`mypy` correctly and install our custom plugin:```ini
# In setup.cfg or mypy.ini:
[mypy]
plugins =
mypy_extras.plugin.entrypoint
```We also recommend to use the same `mypy` settings [we use](https://github.com/wemake-services/wemake-python-styleguide/blob/master/styles/mypy.toml).
## Usage
### AttrOf
We provide a special type to get named attributes of other types, like so:
```python
from typing_extensions import Literal # or typing on python3.8+
from mypy_extras import AttrOfclass User(object):
def auth(self, username: str, password: str) -> bool:
return False # Just an exampledef get_callback(user: User) -> AttrOf[User, Literal['auth']]:
return user.authuser: 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:
```python
from mypy_extras import ensure_attrclass 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:
```python
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](https://github.com/wemake.services/mypy-extras/blob/master/LICENSE)