How to call Python functions dynamically
If don't want to use globals, vars
and don't want make a separate module and/or class to encapsulate functions you want to call dynamically, you can call them as the attributes of the current module:
import sys
...
getattr(sys.modules[__name__], "clean_%s" % fieldname)()
What's the way to call a function dynamically in Python?
Functions are first class objects. So like this:
def do_this():
print "In do_this"
def do_that():
print "In do_that"
dct = [do_this, do_that]
dct[0]()
If you really want to call them from a string list you can use globals():
dct = ['do_this', 'do_that']
globals()[dct[0]]()
But I would suggest that using globals() (or locals()) probably isn't the right way to solve your problem. Grok the python way: >>> import this
How to generate dynamic function name and call it using user input in Python
if the mapping is static, either make a mapping of function name to function object
mapping = {
"pattern_1": pattern_1,
"pattern_2": pattern_2
}
#do not use `eval` on user input!
pattern_no = input('Enter pattern num [1-10]: ')
cust_fun_name = 'pattern_' + str(pattern_no)
cust_func = mapping[cust_fun_name]
# call the function
cust_func()
or get the function object directly from the local namespace
cust_func = locals()['pattern_' + str(pattern_no)]
cust_func()
Dynamic Function Calling From a Different File - Python
In file1.py, add a function dictionary like this:
function_dict = {'one':one, 'two':two, 'three':three}
Then in file2.py, replace file1.function_id()
with this:
file1.function_dict[function_id]()
How to dynamically create functions in python
Just found out the answer. The best way to dynamically create the function is to not create it at all. It kind of conflicts with my question but still solves the problem. The idea is to put a structure of a function as key in a dictionary and a line of the beginning of the function as a value. So now it is possible by structure of the function find it, execute and then return to normal execution by saving the last line of Main in advance.
Calling a function of a module by using its name (a string)
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.
How to dynamically call different functions based on user input
Since functions are objects in Python, it's easy to make a dictionary pairing keywords with functions.
action_dict = {'add': add,
'sub': sub,
# ...
}
if operation in action_dict:
action_dict[operation](num1, num2)
How to call Python function by name dynamically using a string?
You can use the getattr
function:
import torchvision
model_name = 'resnet18'
model = getattr(torchvision.models, model_name)(pretrained=configs.use_trained_models)
This essentially is along the lines the same as the dot notation just in function form accepting a string to retrieve the attribute/method.
Related Topics
How to Timeout Function in Python, Timeout Less Than a Second
How to Extract Text and Text Coordinates from a PDF File
Execute a Function After Flask Returns Response
Python Unittest.Testcase Execution Order
How Come a File Doesn't Get Written Until I Stop the Program
Why Do Attribute References Act Like This with Python Inheritance
How to Strip the Whitespace from Pandas Dataframe Headers
Matplotlib: How to Prevent X-Axis Labels from Overlapping
Numpy Np.Apply_Along_Axis Function Speed Up
Running an Interactive Command from Within Python
Constructing a Co-Occurrence Matrix in Python Pandas
Pip Ignores Dependency_Links in Setup.Py
Django Query That Get Most Recent Objects from Different Categories
Python Super() Raises Typeerror
Except-Clause Deletes Local Variable