import imp def get_module(): m = imp.new_module('jkp') exec 'def f(): g()\n\ndef g(): print "hi"\n' in m.__dict__ return m get_module().f()