0
  • I want to get inner function result so i code it like

     def main():
       def sub():
          a = 1
          print a
     exec main.__code__.co_consts[1]
    
  • using above code working successfully but i want to pass the argument to the sub function like...

    def main():
      def sub(x):
         a = x + 1
         return a
    ans = exec main.__code__.co_consts[1]
    print ans
    
  • in that problem is i don't know how to pass that x value.

  • that work must need to exec so that how to pass that x value with exec without interaction of main function
Virbhadrasinh
  • 529
  • 6
  • 19
  • Why do you need this, what's the real problem you're trying to solve? Nested functions don't seem like the proper solution if you're going to call the inner function without using the outer function. – Markus Meskanen Feb 10 '15 at 09:08
  • I need it into my code but moderate gives instructions exec function must so that is my actual problem – Virbhadrasinh Feb 10 '15 at 09:09
  • I will ask you the same question. Why do you need to bypass the outer function to get to the inner function? Why do you have an inner function in the first place if you will go through the hacks just to make a function calls. Something is not right with this approach even if you manage to get it working. There should be more pythonic solutions to your problem. – dopstar Feb 10 '15 at 10:02
  • As about your comment @dopstar I just want to be a bypass because in main function i need the some other value and from inner inner function need some other value , that also reason because its about my logic. after than that why nested function use because of i want to use main functions parameter and inner function parameter and without class concept so that,thank to interest in my question if you help me than please i thankful to you – Virbhadrasinh Feb 11 '15 at 04:50
  • All the worries of the inner function working and its parameters should not concern you outside the outer function. Instead ask your self what are you doing wrong to be at the point of going through all of this. You should "not see" the inner function at all outside the outer function. Remember your code should not just work, it should be simple and easy to be read and understood by someone else. I would say rather spend time to think about your logic and then implement a right solution. There is closure between the inner and outer function, you could use that for inner function state/memory. – dopstar Feb 12 '15 at 06:54

1 Answers1

1

Maybe something like the code below, as suggested by this SO answer

def main():
    def sub():
        a = x + 1
        print a
        return a
exec(main.__code__.co_consts[1], {'x': 1} )
Community
  • 1
  • 1
ziddarth
  • 1,796
  • 1
  • 14
  • 14