How to Execute Functions Dynamically in Python

There may be times when you want to dynamically execute functions in Python.

If you want to execute function depending on conditions, you’d normally write the following code.

import unittest
class test01(unittest.TestCase):
    def test_helloworld(self):
        function_to_execute = 'foo'
        if function_to_execute == 'foo':
            test01.foo()
        elif function_to_execute == 'bar':
            test01.bar()

    def foo():
        print('hello from foo')

    def bar():
        print('hello from bar')

Writing code like that easily gets unmanageable when there are many conditions. It’s better to dynamically call functions.

import unittest

class test01(unittest.TestCase):
    def test_helloworld(self):
        function_to_execute = 'foo'
        func = getattr(test01, function_to_execute)
        func()

    def foo():
        print('hello from foo')

    def bar():
        print('hello from bar')

You might have quite a bit of functions to manage, the calling method would not be so bad by dynamically calling functions.

Author: admin

A software engineer in greater Seattle area

Leave a Reply

Your email address will not be published. Required fields are marked *