Month: April 2015

Interactive console

The interactive console is probably where everyone starts their programming in Python and remains a great way to try a few lines. How about turning it on it’s head and use an interactive console to work with your code. First the tricky bit of getting an interactive console working; this is the smallest amount of code required.

import code

Now you just need to share the code you have written with the interactive console. You could make all of your code available but this is probably not what you want. Instead construct a dictionary of what you do what available and pass this in as the local dictionary. This has an added advantage in allowing you to alter the names and structure.

import code
def mytest ():
    return "Result from mytest"
# to pass everything in get a copy of the locals dictionary
# mylocals = locals()
mylocals = { "testfn": mytest }

By defining your own dictionary, you can now call testfn() to execute mytest. Nothing else (like the modules imported) have been passed in allowing a cleaner interface.