Short Question
Is it possible to call a module as retrieved from the python dir() function?
Background
I am working on building a custom test runner and would like be able to choose which modules to run based on a string filter. See my examples below for ideal usage.
module_a.py
def not_mykey_dont_do_this():
print 'I better not do this'
def mykey_do_something():
print 'Doing something!'
def mykey_do_somethingelse():
print 'Doing something else!'
module_b.py
import module_a
list_from_a = dir(module_a) # ['not_mykey_dont_do_this', 'mykey_do_something', 'mykey_do_somethingelse']
for mod in list_from_a:
if(mod.startswith('mykey_'):
# Run the module
module_a.mod() # Note that this will *not* work because 'mod' is a string
Output
Doing something!
Doing something else!
getattr(module_a, mod)()
getattr is a builtin function that takes and object and a string, and returns the attribute.
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