• Forward References

    From Jonathan Gossage@21:1/5 to All on Sun Sep 3 16:43:34 2023
    I am attempting to use forward references in my program and I am failing.
    This also does not work with the older way of putting the name of a class
    as a string. Here is some sample code:

    from __future__ import annotations

    from dataclasses import dataclass
    from typing import TypeAlias


    ColorDef: TypeAlias = RGB | int | str



    @dataclass(frozen=True, slots=True)
    class RGB(object):

    Can anyone suggest how I should fix this without reversing the statement
    order?

    pass


    --
    Jonathan Gossage

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From MRAB@21:1/5 to Jonathan Gossage via Python-list on Sun Sep 3 23:56:37 2023
    On 2023-09-03 21:43, Jonathan Gossage via Python-list wrote:
    I am attempting to use forward references in my program and I am failing. This also does not work with the older way of putting the name of a class
    as a string. Here is some sample code:

    from __future__ import annotations

    from dataclasses import dataclass
    from typing import TypeAlias


    ColorDef: TypeAlias = RGB | int | str



    @dataclass(frozen=True, slots=True)
    class RGB(object):

    Can anyone suggest how I should fix this without reversing the statement order?

    pass

    The usual way to deal with forward type references is to use a string
    literal, i.e. 'RGB', but that doesn't work with '|', so use typing.Union instead:

    from typing import TypeAlias, Union

    ColorDef: TypeAlias = Union['RGB', int, str]

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)