Skip to main content

Defining a Custom Unknown Type in Python

Python doesn’t include a built-in unknown type like TypeScript’s. Since unknown can be so helpful, it may be worth creating one yourself.

You can do that by defining a generic type variable:

from typing import TypeVar
 
unknown = TypeVar("unknown")

This is useful anywhere you want Mypy to remind you to make no assumptions about a value’s type:

def unsafe(value: unknown) -> None:
    value.get("some_key")  
    # 🚨 Mypy: "unknown" has no attribute "get"
 
def safe(value: unknown) -> None:
    if not isinstance(value, dict):
        return None
 
    value.get("some_key") 

Using a Generic to mimic unknown is a safer option than Any, which effectively disables type-checking by assuming anything you try to do with a value will work.

Update

Thanks to this helpful discussion of this post, I’ve learned that Python’s built-in object type already works as an “unknown” type, so there’s no need to resort to hacking generics to replicate one.

I’ll leave this post up to avoid a broken link, but let’s all agree to use "object" instead!