Skip to content

Need delayed initializer for self-referential class variables #1176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
alexchandel opened this issue Aug 16, 2023 · 1 comment
Closed

Need delayed initializer for self-referential class variables #1176

alexchandel opened this issue Aug 16, 2023 · 1 comment

Comments

@alexchandel
Copy link

alexchandel commented Aug 16, 2023

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'))
@Tinche
Copy link
Member

Tinche commented Sep 29, 2023

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?

@hynek hynek closed this as not planned Won't fix, can't repro, duplicate, stale Dec 11, 2023
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

No branches or pull requests

3 participants