Search code examples
pythonfunctionbuilt-ingetattrclass-attributes

What is & How to use getattr() in Python?


I read an article about the getattr function, but I still can't understand what it's for.

The only thing I understand about getattr() is that getattr(li, "pop") is the same as calling li.pop.

When and how do I use this exactly? The book said something about using it to get a reference to a function whose name isn't known until runtime, but when and why would I use this?


Solution

  • getattr(object, 'x') is completely equivalent to object.x.

    There are only two cases where getattr can be useful.

    • you can't write object.x, because you don't know in advance which attribute you want (it comes from a string). Very useful for meta-programming.
    • you want to provide a default value. object.y will raise an AttributeError if there's no y. But getattr(object, 'y', 5) will return 5.