import types xyz = 123 def abc(): return xyz assert abc() == 123 # fails new_abc = types.FunctionType( abc.func_code, {'xyz': 456}, abc.func_name, abc.func_defaults, abc.func_closure) assert new_abc() == 456 # this too sm = type(globals())() sm.update({'xyz': 456}) sm_abc = types.FunctionType( abc.func_code, sm, abc.func_name, abc.func_defaults, abc.func_closure) assert sm_abc() == 456