Search code examples
pythonsoftware-design

Overriding __bool__ to check if class exists?


Kind of a design question. I'm initiating a class with an instance variable that will only get its value when the run function is called? Since the data will be the same for all runs I don't want to initialize it over and over again. Should I check if the variable is None or override the bool method? Or is there a better way to achieve this?

class Data:
    def __bool__(self):
        return True

class A:
    def __init__(self):
        self.data = None

    def run_bool(self):
        if not self.data:
            self.data = Data()

    def run_none(self):
        if self.data is None:
            self.data = Data()


Solution

  • Just check if it's None. Defining __bool__ to always return True doesn't do anything, because generic Python objects are truthy anyway, but an explicit None check allows for adding genuine __bool__ behaviour (or switching to a type with such behaviour) later, without breaking things.

    It's not clear from your question, but perhaps what you actually want is functools.cache or functools.cached_property.