Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Python functions dynamically

I have this code:

fields = ['name','email']  def clean_name():     pass  def clean_email():     pass 

How can I call clean_name() and clean_email() dynamically?

For example:

for field in fields:     clean_{field}() 

I used the curly brackets because it's how I used to do it in PHP but obviously doesn't work.

How to do this with Python?

like image 730
nemesisdesign Avatar asked Nov 22 '10 13:11

nemesisdesign


People also ask

How do you call a dynamic function in Python?

Passing arguments to the dynamic function is straight forward. We simply can make solve_for() accept *args and **kwargs then pass that to func() . Of course, you will need to handle the arguments in the function that will be called. Currently, none of the do_ methods in our example accept arguments.

How do you call a function dynamically?

function MyClass() { this. abc = function() { alert("abc"); } } var myObject = new MyClass(); myObject["abc"](); If what you want to do is not only dynamically call a function but also dynamically create a named function, it is also best done with the window object using either: window['name'] = function() { ... }

What is dynamic function in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. Syntax: type(object) The above syntax returns the type of object.


1 Answers

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)() 
like image 164
khachik Avatar answered Sep 22 '22 06:09

khachik