Skip to content

Instantly share code, notes, and snippets.

@antonagestam
Created June 9, 2021 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonagestam/aadd19796444bf3ebe99c7fd065bf475 to your computer and use it in GitHub Desktop.
Save antonagestam/aadd19796444bf3ebe99c7fd065bf475 to your computer and use it in GitHub Desktop.
Recipe for a powerful combination of Literals and phantom types ...
from phantom import Phantom
from typing import Literal, get_args, Union, Mapping
from phantom.predicates.collection import contained
LiteralCountry = Literal["SE", "DE", "DK"]
class PhantomCountry(str, Phantom, predicate=contained(get_args(LiteralCountry))):
...
Country = Union[LiteralCountry, PhantomCountry]
# -- Usage
# Dynamic values can be parsed, e.g. proven to be a valid value at runtime.
some_var = PhantomCountry.parse("DE")
country_populations: Mapping[Country, int] = {
some_var: 60,
# But known valid values don't need to be proven.
"SE": 9,
"DK": 4,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment