0

I am currently trying to read python codebase - I picked up the crayons by Kenneth Reitz as it seems very well written and rather simple, but I am having issues understanding the meaning of the following method (code ref):

...
def __getattr__(self, att):
    def func_help(*args, **kwargs):
        result = getattr(self.s, att)(*args, **kwargs)
        try:
            is_result_string = isinstance(result, basestring)
        except NameError:
            is_result_string = isinstance(result, str)
        if is_result_string:
            return self._new(result)
        elif isinstance(result, list):
            return [self._new(x) for x in result]
        else:
            return result
    return func_help
...

While I have pretty good idea what the magic method __getattr__ does, I kind of struggle seeing the point of returning the function (or how would I use it for that matter).

NefariousOctopus
  • 807
  • 2
  • 10
  • 18
  • Because the user is expecting a callable - this is used in *method* resolution, and wraps the methods on whatever `self.s` is. – jonrsharpe Jan 23 '17 at 21:03
  • @jonrsharpe From docs: `This method should return the (computed) attribute value or raise an AttributeError exception.` I suppose it can be used for any attribute - not exclusively callables. Is this based on assumption (fact actually), that python string has only methods and no properties? – NefariousOctopus Jan 23 '17 at 21:29

0 Answers0