0

I'm aware that the methods __getattribute__ and __getattr__ do not do the same thing; the former is responsible for all attribute access and the latter, if defined, is called when the former raises AttributeError.

What puzzles me is why two similarly named methods related to attribute access even exist for a language that usually tries to eliminate confusion. I can't even think of a situation where I would HAVE to define a __getattr__; I can just define a __getattribute__ that uses object.__getattribute__ in an if statement or try statement. Moreover, the built-in function for attribute access is named getattr which would mislead people into thinking __getattr__ is the go-to method for attribute access. What's the history behind these two methods and is there a good reason they both still exist?

BatWannaBe
  • 4,330
  • 1
  • 14
  • 23
  • `__getattr__` came first. It wasn't good enough, so they added `__getattribute__` to cover the cases `__getattr__` couldn't handle, but they had to keep `__getattr__` for backward compatibility. – user2357112 Jun 14 '19 at 01:32
  • This is a common question and answered thoroughly at https://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute – Deepstop Jun 14 '19 at 01:35
  • 1
    @Deepstop: That answers what the difference is, not why both of these things exist. – user2357112 Jun 14 '19 at 01:36
  • why didn't they just update `__getattr__` instead of making a `__getattribute__` – BatWannaBe Jun 14 '19 at 01:38
  • Backward compatibility. – user2357112 Jun 14 '19 at 02:22
  • 1
    It's not just backwards compatibility. `__getattr__` is a lot easier to use when applicable. It's also possible to use both in the same class. – gilch Jun 14 '19 at 02:31
  • an example illustrating how `__getattr__` is easier or more efficient than a `__getattribute__` with a try statement would be nice a.k.a. an accepted answer – BatWannaBe Jun 14 '19 at 02:44

0 Answers0