Phantom types for Python
Project description
phantom-types
Phantom types for Python will help you make illegal states unrepresentable and avoid shotgun parsing by enabling you to practice "Parse, don't validate".
This project is in early development and fundamental changes should be expected. Semantic versioning will be followed after version 1.0, but before that breaking changes might occur between minor versions.
Checkout the complete documentation on Read the Docs →
Installation
$ python3 -m pip install phantom-types
Examples
By introducing a phantom type we can define a pre-condition for a function argument.
from phantom import Phantom
from phantom.predicates.collection import contained
class Name(str, Phantom, predicate=contained({"Jane", "Joe"})):
...
def greet(name: Name):
print(f"Hello {name}!")
Now this will be a valid call.
greet(Name.parse("Jane"))
... and so will this.
joe = "Joe"
assert isinstance(joe, Name)
greet(joe)
But this will yield a static type checking error.
greet("bird")
Runtime type checking
By combining phantom types with a runtime type-checker like beartype or typeguard, we can achieve the same level of security as you'd gain from using contracts.
import datetime
from beartype import beartype
from phantom.datetime import TZAware
@beartype
def soon(dt: TZAware) -> TZAware:
return dt + datetime.timedelta(seconds=10)
The soon
function will now validate that both its argument and return value is
timezone aware, e.g. pre- and post conditions.
Pydantic support
Phantom types are ready to use with pydantic and have integrated
support out-of-the-box. Subclasses of Phantom
work with both
pydantic's validation and its schema generation.
class Name(str, Phantom, predicate=contained({"Jane", "Joe"})):
@classmethod
def __schema__(cls) -> Schema:
return super().__schema__() | {
"description": "Either Jane or Joe",
"format": "custom-name",
}
class Person(BaseModel):
name: Name
created: TZAware
print(json.dumps(Person.schema(), indent=2))
The code above outputs the following JSONSchema.
{
"title": "Person",
"type": "object",
"properties": {
"name": {
"title": "Name",
"description": "Either Jane or Joe",
"format": "custom-name",
"type": "string"
},
"created": {
"title": "TZAware",
"description": "A date-time with timezone data.",
"type": "string",
"format": "date-time"
}
},
"required": ["name", "created"]
}
Development
Install development requirements, preferably in a virtualenv:
$ python3 -m pip install .[test,pydantic,phonenumbers]
Run tests:
$ pytest
# or
$ make test
Linting and static type checking is setup with pre-commit, after installing it you can setup hooks with the following command, so that checks run before you push changes.
# configure hooks to run when pushing
$ pre-commit install -t pre-push
# or when committing
$ pre-commit install -t pre-commit
# run all checks
$ pre-commit run --all-files
# or just a single hook
$ pre-commit run mypy --all-files
In addition to static type checking, the project is setup with pytest-mypy-plugins to test that exposed mypy types work as expected, these checks will run together with the rest of the test suite, but you can single them out with the following command.
$ make test-typing
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 phantom-types-0.15.1.tar.gz
.
File metadata
- Download URL: phantom-types-0.15.1.tar.gz
- Upload date:
- Size: 20.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.7.1 importlib_metadata/4.10.1 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 38847849b9ecbea857464d5d8bb46b2accb383b616d90fe404ced20385b694c9 |
|
MD5 | a031f26ca214ad54ce97b901a29fcff2 |
|
BLAKE2b-256 | 0dcb2983e1f7ea314c870cd1268430660347d54d95508de2f3170c85d532ca4d |
File details
Details for the file phantom_types-0.15.1-py3-none-any.whl
.
File metadata
- Download URL: phantom_types-0.15.1-py3-none-any.whl
- Upload date:
- Size: 24.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.7.1 importlib_metadata/4.10.1 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 991d22dc50fa6e35a84da40948d4dcd5f78b59b3209daeea829843791ed0159c |
|
MD5 | ee5d318984d9d8e472cf21634bb34e62 |
|
BLAKE2b-256 | ed1d52fec4b4f4dda64b15b5e5d5cfeb685005ad457afe8bc0e971cd3791a038 |