0

I have:

class MyClass:
  my_var: Optional[str] = None

  @classmethod
  def get_my_var(cls) -> str:
    """ Sets cls.my_var if it's not set before """
    my_var = cls.my_var
    if my_var is not None:
       return my_var
    my_var = cls.some_func()
    cls.my_var = my_var
    return my_var

This reason I do this, instead of setting my_var in self.__init__() is because MyClass is often used without an instance, e.g.: MyClass.my_var and the callers expect my_var to have a default value from cls.some_func()

How can I achieve this in python 3.8+? Can I do a @property decorator here? Can I force MyClass to assign my_var a value from cls.some_func()?

martineau
  • 119,623
  • 25
  • 170
  • 301
user1008636
  • 2,989
  • 11
  • 31
  • 45
  • What have you tried, what happened? – thebjorn May 27 '22 at 19:40
  • 2
    Does this answer your question? [Using property() on classmethods](https://stackoverflow.com/questions/128573/using-property-on-classmethods) – Marat May 27 '22 at 19:41
  • 1
    Why are you deferring the initialization of the *class* attribute in the first place? A class attribute should be something that describes the *class*, independent of how many instances of the class exist. – chepner May 27 '22 at 19:47
  • 1
    A much simpler way to write `get_my_var` anyway would be `if cls.my_var is None: cls.my_var = cls.some_func()`, then `return cls.my_var`. – chepner May 27 '22 at 19:48
  • I mean, you can just do `MyClass.my_var = MyClass.some_func()` right after the class definition. – juanpa.arrivillaga May 27 '22 at 20:10
  • 1
    I don't understand, once class with a class variable of `my_var = None` has been initialized so has the class variable... They are initialized with the class definition at runtime – Alexander May 27 '22 at 20:15
  • @alexpdev yeah, I mean, it's a good point -- in Python, variables are simply defined, there is no seperate declaration/initialization step. `my_var = None` **is defining a variable, which is identical to "initializing it"**. But I think the OP means how to give it a value other than `None` – juanpa.arrivillaga May 27 '22 at 22:01

0 Answers0