func_code vs. string problem

Filip Dreger fdreger at amiga.pl
Sat Apr 23 12:28:13 EDT 2005


Each function has a func_code property that is suposed to contain the 
pure bytecode of the function. All the context (including reference to 
relevant namespaces) is stored in different fields of the function 
object. Since 'exec' is able to execute any string or bytecode in the 
current scope, it would seem possible to execute code of any function 
in any namespace. But no matter how I tried, I could not do it. There 
must be something I am missing.
Here's what I do:    (if anyone wants to help, I placed the source 
under http://www.bajobongo.net/foo.py - tested on Python 2.4.1)

1. I declare a function. In the next steps I will try to run its code 
from inside a class:

def myfunction():
   print abc
   self.test()

2. I declare a class foo, with two methods. The first one tries to 
reach some local variables from a string passed to exec. The other one 
tries to do the same from inside a bytecode (from myfunction). IMHE 
this should make no difference to 'exec' - [spoiler: it does].

class foo:
   def test(self):
      print "ABC"
   def checkfunction(self):
      abc=10
      exec myfunction.func_code
   def checkstring(self):
      abc=10
      exec "print abc;self.test()"

3. I test the both methods. Sadly, the 'checkfunction' fails to find 
the correct namespace (id does not see 'abc' nor 'self'). Adding 
things like:
"exec myfunction.func_code in globals(),locals()" does not help.

i=foo()
i.checkstring()
i.checkfunction()  # this throws exception; why???

4. I try to find some help here, and hope to also gain better 
undesrtanding of how Python works :-)

Thanks for any suggestions,
regards,
Filip Dreger 





More information about the Python-list mailing list