Skip to content

Need delayed initializer for self-referential class variables #1176

Closed as not planned
@alexchandel

Description

@alexchandel

Consider the following example of a class with a class variable that is an instance of itself. It's impossible to reference class names within the immediately body of the class, as the class is not defined yet:

define
class SolverBackend:
    name: SolverName = field(converter=SolverName)

    SCIP: ClassVar[Self] = SolverBackend('scip')  # ERROR

Instead, you have to do something like ths:

@define
class SolverBackend:
    name: str

    SCIP: ClassVar[Self]

SolverBackend.SCIP = SolverBackend('scip')

(This is an extremely simplified example to demonstrate this aspect.) It would be nice to support this natively, with something like:

@define
class SolverBackend:
    name: str

    SCIP: ClassVar[Self] = classvar(factory=lambda: SolverBackend('scip'))

Or maybe just interpret the usual attrs functions appropriately for ClassVar, like:

@define
class SolverBackend:
    name: str

    SCIP: ClassVar[Self] = Factory(lambda: SolverBackend('scip'))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions