Skip to content

[Feature]: Type inference with generics enum #1517

@nicolaassolini-qntm

Description

@nicolaassolini-qntm

Problem Statement

Enum generics with type inference open some open questions (some examples below).

Proposed Solution

No response

Component

No response

Effort Estimate

None

Additional Context

The main issue regards how we can handle type inferences when we have some variant with generics but some other without it.

For instance, this is fine:

T = guppy.type_var("T")

@guppy.struct
class Sa(Generic[T]):
    x: T

@guppy.enum
class EnumA(Generic[T]):
    VariantA = {"x": T}
    VariantB = {"y": bool}

@guppy
def mian() -> None:
    a = Sa(5)
    b = EnumA.VariantA(a)

This fails:

@guppy
def main() -> None:
    y = EnumA.VariantA(False)
    z = EnumA.VariantB(True) # Error: Cannot infer type

while this works:

@guppy
def main_explicit() -> None:
    y = EnumA.VariantA(False)
    y = EnumA.VariantB[int](False)

More complex examples are:

@guppy.enum
class EnumA(Generic[T]):
    VariantA = {"x": T}
    VariantB = {"y": bool}

@guppy
def function(b: bool) -> EnumA[bool]:
    return EnumA.VariantB(b)

@guppy
def main_variant() -> None:
    a = function(False) # This works!

This fails (properly)

@guppy.enum
class EnumA(Generic[T]):
    VariantA = {"x": T}
    VariantB = {"y": bool}

@guppy
def foo(x: EnumA[int]) -> None:...

@guppy
def bar(y: EnumA[float]) -> None:...

@guppy
def main_ambiguity() -> None:
    z = EnumA.VariantA(False)
    foo(z) # Type mismatch: Expected argument of type `EnumA[int]`, got `EnumA[bool]`
    bar(z)
@guppy
def control_flow_example(flag: bool) -> EnumA[int]:
    if flag:
        result = EnumA.VariantA(42)
    else:
        result = EnumA.VariantB(True) # Error: Cannot infer type
    return result
@guppy
def control_flow_example(flag: bool) -> EnumA[int]:
    if flag:
        result = EnumA.VariantA(42)
    else:
        result = EnumA.VariantB[int](True)
    return result # This is fine!

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature requestC-questionCategory: User questions that are neither a feature nor a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions