Uzytkownik "Steven Bethard" <[EMAIL PROTECTED]> napisal w wiadomosci news:[EMAIL PROTECTED]
> See the documentation: > > http://docs.python.org/ref/dynamic-features.html > > """The eval(), execfile(), and input() functions and the exec > statement do not have access to the full environment for resolving > names. Names may be resolved in the local and global namespaces of > the caller. Free variables are not resolved in the nearest enclosing > namespace, but in the global namespace.""" Thank you! I feel silly I have not found the piece of instruction myself. And even worse, as I still do not understand: if exec() resolves free bariable names in the global namespace, how come it works well with code in a string? Or with a code in a compiled string? > Note the last sentence, which tells you that your free variable, > 'abc', will be resolved in the *global* namespace. In your > particular problem, you can solve this by substituting your local > namespace for the global namespace. This particular problem - sadly - is a simplified version of the real one. I need access to both: global and local namespaces, so this solution is not for me. The manual says I can pass two dictionaries to exec, one for global namespace and one for local. But, strange as it seems, I could not get it to work. In the example I gave, changing exec f.func_code to exec f.func_code in globals(),locals() does not help a bit. > One possible workaround might be: > > py> class foo: > ... def test(self): > ... print "ABC" > ... def checkfunction(self): > ... abc=10 > ... l = locals() > ... l.update(globals()) > ... exec myfunction.func_code in l > ... def checkstring(self): > ... abc=10 > ... exec "print abc;self.test()" > ... > py> foo().checkfunction() > __main__.foo > 10 > ABC I thought about that... I don't know why, but it seems wrong. Maybe the updating dictionaries is not very expensive, but there must be some better way. This code has a 'workaround - fixme' written all over it. Up to now, each time I encountered such a workaroundish solution, it turned out Python has a cleaner way to do it. I sure hope this is also the case here :-). > But I'd have to know what your real use case is to tell you whether > or not this is worth the trouble. Why do you want to exec the > func_code anyway? Why can't you just call the function? I put the description in the other post. Perhaps it's jkust my design that's broken. Thanks again. regards, Filip Dreger -- http://mail.python.org/mailman/listinfo/python-list