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?
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.
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() { ... }
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.
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)()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With