How to Invoke a Method Dynamically in Python (Reflection)

Sometimes you want to be able to invoke a method dynamically rather than calling it explicitly. Or in other words, let’s say you have a bunch of methods, and you have a string object telling you which method to execute, but rather than doing a bunch of if statements you want to be able to able to let Python figure out which method it is. In other languages (e.g. Java and C#), this is called Reflection. In Python, you can use a function called getattr to do this. The name is not the most descriptive, but that’s OK.

Anyway, this article gives a nice summary of how to do this.

Leave a Reply