Created
June 9, 2021 08:47
-
-
Save antonagestam/aadd19796444bf3ebe99c7fd065bf475 to your computer and use it in GitHub Desktop.
Recipe for a powerful combination of Literals and phantom types ...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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