7

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!
1
  • testoob allows you to select tests using regex. You can see how they do it, or just use the whole framework if it fits your needs. Commented Oct 26, 2011 at 2:37

2 Answers 2

7
getattr(module_a, mod)()

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

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. I wish I would have looked a bit closer in the built in functions.
5

Sure:

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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.