Skip to content

Conversation

@dbrattli
Copy link
Collaborator

@dbrattli dbrattli commented Jan 10, 2026

Background

For Python we would like a Discriminated Union (DU) type that

  1. Preserves type safety - Python type checkers (pyright, mypy) should understand the union structure
  2. Enables pattern matching - Python 3.10+ match statements should work naturally with case extraction
  3. Provides good IDE support - Autocomplete, go-to-definition, and hover documentation should work
  4. Maintains backwards compatibility - Existing Fable Python code using .tag and .fields should continue to work
  5. Follows Python conventions - The generated code should look and feel like idiomatic Python

This PR changes the generated Union code:

F# Source

type MyUnion =
    | CaseA of int
    | CaseB of string
    | CaseC of x: float * y: float

Generated Python Output

from fable_library.union import Union, tagged_union

# Base class with underscore prefix (private/internal)
class _MyUnion(Union):
    """Base class inheriting from Union for compatibility."""

    @staticmethod
    def cases() -> list[str]:
        return ["CaseA", "CaseB", "CaseC"]


@tagged_union(0)
class MyUnion_CaseA(_MyUnion):
    item: int


@tagged_union(1)
class MyUnion_CaseB(_MyUnion):
    item: str


@tagged_union(2)
class MyUnion_CaseC(_MyUnion):
    x: float
    y: float


# Type alias - THE public union type for annotations
type MyUnion = (MyUnion_CaseA | MyUnion_CaseB) | MyUnion_CaseC

Closes: #3558

@github-actions
Copy link

Python Type Checking Results (Pyright)

❌ Type errors found in non-excluded files

Metric Value
Excluded files 3
Files excluded from type checking

These files have known type errors and are excluded from CI. Remove from pyrightconfig.ci.json as errors are fixed.

temp/tests/Python/fable_modules/thoth_json_python/encode.py
temp/tests/Python/test_applicative.py
temp/tests/Python/test_misc.py

@dbrattli dbrattli changed the title [Python] Redesign Union type [Python] Redesign Discriminated Union (DU) type Jan 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants