Saturday, 15 September 2012

python - Why doesn't exec work in a function with a subfunction? -


It seems that you can not use exec in a function that contains subfunction ...

< P> Anyone know why this python code does not work? I get an error in exec2 in test2 Also, I know that the exec's style is not good, but I believe, I am using exec for the proper reason. I will not use it otherwise.

pre / #! / Usr / bin / env python # def test1 (): exec ('print' from hello test1 '') test1 () def test2 (): "Test with a subfunction." "Digit (from 'print' hi 'test2') Def subfunction (): Return true test2 ()

EDIT: I bug down to the function in a subfunction compressed. Nothing to do with elaboration keyword.

Correct. You can not use exec in a function , In which there is no subfunction, unless you specify a reference. From the docs:

If the function is used in the function and the function If the machine has a nested block with free variables, then the compiler will increase a syntax array, unless the exec specifies the local namespace to execute. (In other words, "obz ozz" will be invalid, but "in ns obz Obj "will be legal.)

There is a good reason for this that I can understand what it was on Sunday night now, next question: Why are you using exec? very Have required Uskil you say you feel doubt a good reason for me about this;) If you have a good reason, so I'll tell you workaround. : - P

Oh okay, here it is anyway:

  def test2 (): "" "Test with a subfunction" "" "" Print " Hi Test2 "'in globals (), local () def subfunction (): return True  

No comments:

Post a Comment