1

Seems like an obvious question, but I can't find the answer.

In Python, how do I initialise class data (not instance attributes).

class MyClass:
    DATA = MyClass()

Doesn't work, because MyClass() isn't defined yet.

class MyClass:
    pass

MyClass.DATA = MyClass()

Is confusing to the human reader, linter, IDE and autocomplete.

Is there a more standard way of doing this?

0

1 Answer 1

1

You can't. You should typehint it and define it afterwards:

class MyClass:
    DATA: ClassVar['MyClass'] # Will get set afterwards
MyClass.DATA = MyClass()

This should solve the problem for autocomplete(IDE) and human reader. Should also be ok for most linter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.