{"library":"phantom-types","title":"Phantom Types for Python","description":"phantom-types is a Python library that enables the creation of 'phantom types' to enforce type safety at compile time without incurring runtime overhead. It leverages Python's `__instancecheck__` protocol and boolean predicates to allow developers to define stricter type constraints, helping to make 'illegal states unrepresentable' and mitigate 'shotgun parsing'. The library is currently at version 3.0.2 and follows semantic versioning after its 1.0 release, with new versions released periodically to add features, fix bugs, and maintain compatibility.","language":"python","status":"active","last_verified":"Thu Apr 16","install":{"commands":["pip install phantom-types","pip install phantom-types[all]"],"cli":null},"imports":["from phantom import Phantom","from phantom.predicates.collection import contained","from phantom.datetime import TZAware"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"from phantom import Phantom\nfrom phantom.predicates.collection import contained\nfrom typing import TYPE_CHECKING\n\n# Define a phantom type 'Name' that only accepts 'Jane' or 'Joe'\nclass Name(str, Phantom, predicate=contained({\"Jane\", \"Joe\"})):\n    pass\n\ndef greet(name: Name):\n    print(f\"Hello {name}!\")\n\n# Valid usage: explicitly parsing a value into the phantom type\ngreet(Name.parse(\"Jane\"))\n\n# Valid usage: using runtime type checking (e.g., isinstance) to narrow the type\njoe = \"Joe\"\nassert isinstance(joe, Name) # This assertion informs type checkers\ngreet(joe)\n\n# This call would typically be caught by a static type checker like MyPy\n# as 'bird' does not satisfy the predicate for 'Name'.\n# if TYPE_CHECKING:\n#     greet(\"bird\") # E.g., Uncommenting this line would cause a MyPy error\n","lang":"python","description":"This quickstart demonstrates how to define a simple phantom type `Name` that narrows the `str` type to only accept specific values ('Jane' or 'Joe'). It shows both explicit parsing using `Name.parse()` and leveraging Python's `isinstance()` for type narrowing recognized by static type checkers. Invalid inputs are caught at compile time by type checkers, preventing runtime errors.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}