Get Function from Modules Using Its Name

Python
How to get the function defined in the current module using its name.
Author

Ziyue Li

Published

January 19, 2023

Sometimes we need to obtain a function defined in a certain module using its name. If the function you are calling is defined in the same module, we can use globals() or locals():

def demo_func(*args, **kwargs):
    pass


def test_locals(*args, **kwargs):
    "Test whether we can get the local functions using locals()"
    def local_demo_func(self, *args, **kwargs):
        pass

    return locals()['local_demo_func'] == local_demo_func


# `globals()` returns a dictionary with the global symbol table:
assert globals()['demo_func'] == demo_func
# `locals()` returns a dictionary with the current local symbol table
assert test_locals()

If it’s defined another module, we can simply do

import foo

func = getattr(foo, 'demo_func')

For example:

from datetime import date

assert getattr(date, 'today') == date.today