Search code examples
pythongetattribute

Object has no attribute Error when calling __getattribute__ on singleton object


This is singleton object I implemented quickly (very similar to second example from The Singleton template).

class Model(object):
  class __Model:
    def __init__(self):
        self.val = None

    def __str__(self):
        return repr(self) + self.val

    instance = None

    def __new__(cls):  # __new__ always a classmethod
        if not Model.instance:
            Model.instance = Model.Model()
        return Model.instance

    def __getattr__(self, name):
        return getattr(self.instance, name)

    def __setattr__(self, name):
        return setattr(self.instance, name)

    def __getattribute__(self, bool_custom_trained):
        return getattr(self.instance, bool_custom_trained)

    def __setattr__(self, bool_custom_trained):
        return setattr(self.instance, bool_custom_trained)

I'm using that object in two scripts. In first

print(self.model.__getattribute__('bool_custom_trained'))

Printing and setting attribute value works fine, but in second I can't use value, generated error is:

    **print(self.model.__getattribute__('bool_custom_trained'))
AttributeError: 'Model' object has no attribute 'bool_custom_trained'**

What should I check?


Solution

    1. Throw that entire book (python-3-patterns-idioms-test.readthedocs.io, “Python 3 Patterns, Recipes and Idioms”) away.

    2. Create an instance, because this isn’t Java.

      from dataclasses import dataclass
      
      
      class Model:
          def __init__(self):
              self.name = ''
              self.bool_custom_trained = False
      
      
      model_instance = Model()
      
    3. If you don’t trust yourself not to create more Models, you can del Model afterwards.