Need delayed initializer for self-referential class variables
alexchandel opened this issue · 1 comments
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'))
If I understand correctly, I think this is a neat idea but somewhat out of scope for attrs and a little bit of a niche use case. You could probably do this youself by wrapping @define
with your own function and running a little bit of post processing?