Python __attrs__ explained

This is not a standard Python thing. As far as I can tell, it's only there to be used in the __getstate__ method further down the class:

def __getstate__(self):
    state = dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)
    state['redirect_cache'] = dict(self.redirect_cache)
    return state

The name __attrs__ is a poor choice, as names beginning and ending with __ are reserved for core Python language features.


It is not standard, because it is not part of the Python Object Model.

The requests module uses it here (Response object), too, for reference

It just a way to keep some state hidden (at least as hidden as possible, because nothing is truly hidden in Python).

The writers of this code just delegate to this dictionary using a call that is part of the Python Object Model getattr:

return {attr: getattr(self, attr, None) for attr in self.__attrs__}

Tags:

Python