Skip to main content

Phantom types for Python

Project description


Phantom types for Python.


python3 -m pip install phantom-types



Builtin types


  • TZAware
  • TZNaive


  • Natural
  • NegativeInt
  • Portion

  • Match


  • NonEmpty
  • Empty

Creating phantom types

To create new phantom types, subclass phantom.base.Phantom and define an __instancecheck__ method:

from typing import Any
from typing import TYPE_CHECKING

from phantom.base import Phantom

class Greeting(str, Phantom):
    def __instancecheck__(cls, instance: Any) -> bool:
        return (
            isinstance(instance, str)
            and instance.startswith(("Hello", "Hi"))

hello = "Hello there"
# We can narrow types using mypy's type guards
assert isinstance(hello, Greeting)
# or explicitly when we need to
hi = Greeting.from_instance("Hi there")

# The runtime types are unchanged and will still be str for our greetings
assert type(hello) is str
assert type(hi) is str

# But their static types will be Greeting, retaining the information that our
# strings are not just any strs

# As this string doesn't fulfill our __instancecheck__, it will not be an
# instance of Greeting.
assert not isinstance("Goodbye", Greeting)

Checkout out the dacite example for how to create dataclasses with rich phantom-typed fields without duplicating type definitions or losing parsed information.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for phantom-types, version 0.0.2
Filename, size File type Python version Upload date Hashes
Filename, size phantom_types-0.0.2-py3-none-any.whl (8.6 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size phantom-types-0.0.2.tar.gz (6.5 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page