Request for exec/namespace advice
John Allison
My_first_name at malinger_dot_org
Fri Oct 10 19:40:58 EDT 2003
Hi everybody
I'm very new to python so please forgive any idiotic mistakes:
I'm writing a MUD-like text game in python and I want to support dynamic
ingame scripting to deal with user commands.
I have a database table containing command strings and python code. When a
player types a command, the program looks up the table for the command and
executes the corresponding python code.
My plan was initally to build a library of useful functions and include
these in a namespace which I'd use with exec to run the python scripts.
I have the following example code(simplified for clarity):
# --- Start code snippet
class scripter:
"""Library of functions for the scripting engine."""
def __init__(self, currentPlayer):
self.me = currentPlayer
def message(self, text):
self.me.write(text)
def runCommand(cmd, user):
"""Carry out an instruction for a particular entity"""
namespace = {"s" : scripter(user)}
exec(cmd, namespace)
# --- end code snippet
Thus I can run scripts such as:
s.message("Hello World.\n")
What I want to do is call the methods without having to qualify them with
the class instance variable(s). I had assumed this would be a trivial matter
of manipulating namespaces but so far it has eluded me.
I have tried things like: (It throws an error)
namespace = scripter.__dict__
namespace.update(scripter().__dict__)
exec(cmd, namespace)
Am I on the wrong track here, and is there a better way to accomplish this?
Note: I realise there are security issues with exec: currently this is just
a fun project for me to learn the language, this is more a question on
namespaces than on pros and cons of exec...
My thanks
John
More information about the Python-list
mailing list