I can put an import statement in a string, exec it, and it works (prints a random digit):
code = \"\"\" import random def f(): print random.randint(0,9)
How about this:
def test(): exec (code, globals()) f()