Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling modules from Python dir()

Tags:

python

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!
like image 349
Adam Lewis Avatar asked Oct 26 '11 02:10

Adam Lewis


1 Answers

getattr(module_a, mod)()

getattr is a builtin function that takes and object and a string, and returns the attribute.

like image 120
Winston Ewert Avatar answered Sep 20 '22 02:09

Winston Ewert