Steven Bethard wrote: > André Roberge wrote: > > Behind the scene, I have something like: > > robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } > > and have mapped move() to correspond to > > robot_dict['robot'].move() > > (which does lots of stuff behind the scene.) > > > > I have tested robot_dict[] with more than one robot (each with > > its own unique name) and am now at the point where I would like > > to have the ability to interpret something like: > > > > alex = CreateRobot() > > anna = CreateRobot() > > > > alex.move() > > anna.move() > > > > etc. Since I want the user to learn Python's syntax, I don't > > want to require him/her to write > > alex = CreateRobot(name = 'alex') > > to then be able to do > > alex.move() > > How do you get the commands from the user? Maybe you can preprocess the > user code? > > py> class Robot(object): > ... def __init__(self, name): > ... self.name = name > ... def move(self): > ... print "robot %r moved" % self.name > ... > py> user_code = """\ > ... alex = Robot() > ... anna = Robot() > ... alex.move() > ... anna.move()""" > py> new_user_code = re.sub(r'(\w+)\s+=\s+Robot\(\)', > ... r'\1 = Robot(name="\1")', > ... user_code) > py> print new_user_code > alex = Robot(name="alex") > anna = Robot(name="anna") > alex.move() > anna.move() > py> exec new_user_code > robot 'alex' moved > robot 'anna' moved >
Smack! (sound of hand slapping forehead). Of course! This is *much* better. (In all honesty, I have trouble reading regular expression notation but I can decode it enough to understand that I can do this - and I already asked a question today on the list about regular expressions, so I have not excuse for not having thought of an approach like this.) I will be already 'processing' the code to make sure that statements/words like: import, exec, eval, input, raw_input, vars, chr, .... are not allowed in the user-defined instructions. This will be just a simple addition. Once again, thank you! Both for this, and for the other example which taught me something about the use of locals(), globals(), and functions that return classes. There are so many corners of Python to explore :-) > Steve -- http://mail.python.org/mailman/listinfo/python-list