Better duck-typing with mypy-compatible extensions to Protocol
Project description
If it walks like a duck and it quacks like a duck, then it must be a duck
Thanks to PEP544, Python now has protocols: a way to define duck typing statically. This library gives you some niceties to make common idioms easier.
Installation
pip install quacks
⚠️ For type checking to work with mypy, you’ll need to enable the plugin in your mypy config file:
[mypy]
plugins = quacks.mypy
Features
Easy read-only protocols
Defining read-only protocols is great for encouraging immutability and working with frozen dataclasses. Use the readonly decorator:
from quacks import readonly
@readonly
class User(Protocol):
id: int
name: str
is_premium: bool
Without this decorator, we’d have to write quite a lot of cruft, reducing readability:
class User(Protocol):
@property
def id(self) -> int: ...
@property
def name(self) -> str: ...
@property
def is_premium(self) -> bool: ...
Partial protocols (work in progress)
What if you want to reuse parts of a protocol? Imagine we have several functions who use various properties of User. With partial protocols you can reuse attributes without having to define many overlapping protocols. Inspired by clojure spec.
(exact syntax TBD)
class User(Protocol):
id: int
name: str
is_premium: bool
address: Address
class Address(Protocol):
street: str
city: str
country: str
from quacks import _
def determine_discount(u: User[_.id.is_premium]) -> int:
... # access `id` and `is_premium` attributes
def greet(u: User[_.name.address[_.country]]) -> None:
... # access `name` and `address.country` attributes
u: User = ...
determine_discount(u)
greet(u)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file quacks-0.2.0.tar.gz
.
File metadata
- Download URL: quacks-0.2.0.tar.gz
- Upload date:
- Size: 5.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.1.12 CPython/3.9.9 Darwin/21.2.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | a6f9f85e254c2e8c86f497af4dcc828413ee22be40dab3fb466a78c296bb1139 |
|
MD5 | 34ef3d04f798f467e9b05b290de3962d |
|
BLAKE2b-256 | 60396700d42405cba2d0eb2133b4722cdc25180d460884fbdd14d0c81a5e2fbe |
Provenance
File details
Details for the file quacks-0.2.0-py3-none-any.whl
.
File metadata
- Download URL: quacks-0.2.0-py3-none-any.whl
- Upload date:
- Size: 6.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.1.12 CPython/3.9.9 Darwin/21.2.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 290c747ac40403ef4dd72e4d78a50781f7213dda4643e44cb5416c4530fe7c6a |
|
MD5 | c5349dfb4c3f83fbe1c8255b1606b435 |
|
BLAKE2b-256 | 1a5d62992bab8d797bd52180412c7d72f59ae492a3daafb55a885ecb19a85567 |