Request for exec/namespace advice

J

John Allison

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top