[Tutor] getattr help

Peter Otten __peter__ at web.de
Sat Mar 10 10:05:36 CET 2012

mjolewis at gmail.com wrote:

> What is the purpose of getattr? Why not just use help or am I completely
> misunderstanding this?
>>From what I read, getattr allows you to get a reference to a function
>>without knowing its name until runtime.
> However, the example provided is:
> li = ['larry', 'curly]
> getattr(li, 'pop')
> It seems to me that I need to know the name of the function to use
> getattr?

The name need not be known *until* *runtime*. You can pass it as a variable 
which makes the program more flexible. Here is an example:

$ cat getattrdemo.py 
class Joe:
    def run(self):
    def jump(self):
    def say_hello(self):
        print("Hello, I am Joe")

class Sue:
    def say_hello(elf):
        print("Hello, I am Sue")
    def swim(self):

for person in [Joe(), Sue()]:
    actions = [action for action in dir(person) if not 
    print("I can", ", ".join(actions))
    while True:
        action = input("What do you want me to do? ")
        if action == "":
        if action in actions:
            getattr(person, action)()
            print("I'm afraid I can't", action)

The code in the for loop does not "know" what joe or sue can do, it detects 
it at runtime. Therefore you don't have to change it when you add another 
person (as long as it can .say_hello()). 

And here's what you may see when you run the script:

$ python3 getattrdemo.py 
Hello, I am Joe
I can jump, run, say_hello
What do you want me to do? jump
What do you want me to do? run
What do you want me to do? swim
I'm afraid I can't swim
What do you want me to do? 
Hello, I am Sue
I can say_hello, swim
What do you want me to do? say_hello
Hello, I am Sue
What do you want me to do? talk
I'm afraid I can't talk
What do you want me to do? swim
What do you want me to do? 

If you want to see a more advanced example of the technique, have a look at 
cmd.py in Python's standard library.

More information about the Tutor mailing list