Calling modules from the Python () directory

Short question
Is it possible to call a module obtained from python's dir () function?

Background
I am working on creating a special test runner and would like to be able to choose which modules to run based on the string filter. See my examples below for perfect use.

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 

Exit

 Doing something! Doing something else! 
+6
source share
2 answers
 getattr(module_a, mod)() 

getattr is a built-in function that accepts, as well as an object and a string, and returns an attribute.

+6
source

Of course:

 import module_a list_from_a = dir(module_a) for mod in list_from_a: if(mod.startswith('mykey_'): f = getattr(module_a, mod) f() 
+3
source

Source: https://habr.com/ru/post/900100/


All Articles