Search code examples
pythoninfinite-loopgetattribute

Python: how to access an attribute from a __getattribute__ method


I have the following class:

class StrLogger(str):
    def __init__(self, *args):
        self._log_ = []
        str.__init__(self, *args)
    def __getattribute__(self, attr):
        self._log_.append((self.__name__, attr))
        return str.__getattribute__(self, attr)

I can initialize a StrLogger with slog = StrLogger('foo') and I can access all of its inherited methods from str and it runs with no problem. The problem is, when I try to retreive the log with either slog._log_ or slog.__dict__['_log_'], the __getattribute__ method gets stuck in an infinite recursion. I understand why this is happening but my question is, how can I access the log?


Solution

  • Your __getattribute__ should exclude __dict__ and maybe as well _log_ from logging. Alternatively, you could do something like

    slog = StrLogger('foo')
    thelog = slog._log_
    do_stuff_with(slog)
    print thelog
    

    (untested!)