A pretty common use case for
getattr is mapping data to functions.
For instance, in a web framework like Django or Pylons,
getattr makes it straightforward to map a web request’s URL to the function that’s going to handle it. If you look under the hood of Pylons’s routing, for instance, you’ll see that (by default, at least) it chops up a request’s URL, like:
into “customers” and “list”. Then it searches for a controller class named
CustomerController. Assuming it finds the class, it creates an instance of the class and then uses
getattr to get its
listmethod. It then calls that method, passing it the request as an argument.
Once you grasp this idea, it becomes really easy to extend the functionality of a web application: just add new methods to the controller classes, and then create links in your pages that use the appropriate URLs for those methods. All of this is made possible by