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).

2
  • Because the user is expecting a callable - this is used in method resolution, and wraps the methods on whatever self.s is. Commented Jan 23, 2017 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? Commented Jan 23, 2017 at 21:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.