HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCriticalCanonical

Calling a function of a module by using its name (a string)

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
modulefunctionnamecallingusingitsstring

Problem

How do I call a function, using a string with the function's name? For example:

import foo
func_name = "bar"
call(foo, func_name)  # calls foo.bar()

Solution

Given a module foo with method bar:

import foo
bar = getattr(foo, 'bar')
result = bar()


getattr can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.

Code Snippets

import foo
bar = getattr(foo, 'bar')
result = bar()

Context

Stack Overflow Q#3061, score: 2984

Revisions (0)

No revisions yet.