[Tutor] Let imported module access calling program

Kent Johnson kent37 at tds.net
Tue Mar 25 12:22:19 CET 2008

Shrutarshi Basu wrote:
>>  This seems kind of strange to me. You want the entire user module to be
>>  re-run?
> Well perhaps not the entire module, but probably most of it.

How will you know how much to re-run? Reloading a module re-runs *all* 
of it, including reinitializing any global variables...

> Here's an
> example. Suppose you want to define a simple obstacle avoidance
> behavior, the script should be something similar to:
> import robot
> if robot.sensor('front') > 100:
>     robot.left_turn()

A few ideas:

- put all the code that should be repeated into a single function and 
pass that function to a run() function:

def actions():
   if robot.sensor('front') > 100:


- Give the user direct control of the timing:

while robot.is_running():
   if robot.sensor('front') > 100:
   time.sleep(1) # or robot.wait()

- register event handlers for specific events. This is more complex but 
it is also a more flexible execution model than polling at timed intervals:

def handle_sensor_front():

robot.register('sensor', 'front', handle_sensor_front)

- have the user subclass robot and implement handler methods:

class MyRobot(robot):
   def handle_sensor_front(self):

You might want to look at Pyro (Python Robotics) to see how others have 
solved this problem:

> Defining the sensor() and left_turn() functions is no problem, but
> this should be a continuous behavior, hence the need to run it over
> and over at certain time intervals. I already have a config.py
> (accessed by robot.py and a few other modules) which the user can
> modify to set the intervals (and other details). i've also been
> thinking about creating a controller.py which handles the repetition
> and imports the user's code and runs its functions, but i would still
> like to explore this method.
> Thanks again,
> Basu

More information about the Tutor mailing list