4

I'm trying to write a script that takes two Bots and then feeds them to an engine for them to play a game. As an example usage:

$:python rungame.py smartbot.py dumbbot.py
Detected SmartBot in smartbot.py...
Detected DumbBot in dumbbot.py...
Running game...

The problem I'm having is that I have no idea how to detect/get the Bot objects out of the modules that are provided via the command line. (If it helps any, I wouldn't at all mind enforcing conventions.) How do I do this?

2 Answers 2

3

You'd probably need the class name as well a module name. With that, you could use this:

getattr(__import__(module_name), class_name)

If you don't want to make them specify a class name, you might be able to find a class that ends with Bot:

module = __import__(module_name)
clazz = None
for attribute_name in dir(module):
    attribute = getattr(module, attribute_name)
    if attribute_name.endswith('Bot') and callable(attribute):
        clazz = attribute
        break

However:

Explicit is better than implicit. The Zen of Python

So I'd stick with the first approach of letting them specify the module and class name.

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

1 Comment

Although probably unrelated to your application, it appears Werkzeug has some functionality which can import objects like that, too.
1

One of the most common patterns for this problem is to define in your API that the object must have a particular name; For instance, you might call that special variable bot:

# smartbot.py
class SmartBot(object):
    "A very smart bot!"

bot = SmartBot()
# dumbbot.py
class DumbBot(object):
    "A dumb bot bot!"

bot = DumbBot()
# rungame.py
import sys
for source in sys.argv[1:]:
    l = {}
    execfile(source, l)
    bot = l["bot"]
    print "Detected %s in %s..." % (type(bot).__name__, source)
print "Running game..."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.