0

I want to pass few parameters in the python code object. I have tried the below code and it is running fine but I want to know how I can pass the value of a & b externally and assign return variable into another variable c.

codeInString = 'a = 5\nb=6\nsum=a+b\nprint("sum =",sum)\v return sum'
codeObject = compile(codeInString, 'sumstring', 'exec')

exec(codeObject)

Something like this:

codeInString = 'sum=a+b\nprint("sum =",sum) return sum'
codeObject = compile(codeInString, 'sumstring', 'exec')

c = exec(codeObject(a,b))

Please note: I am running this code in a distributed environment.

martineau
  • 119,623
  • 25
  • 170
  • 301
Nikhil Suthar
  • 2,289
  • 1
  • 6
  • 24
  • 1
    You mean like `exec(codeObejct, dict(a=5, b=6))`? Not sure what you mean about globally. – no comment Sep 12 '21 at 10:27
  • yes I want something like this .. exec(codeObejct, dict(a=5, b=6)).. but this is not working .. can you give me how CodeString will be corresponding to this.@don'ttalkjustcode – Nikhil Suthar Sep 12 '21 at 10:37

1 Answers1

0

It seems like you think you're defining a function in the codeInString, but you are not. Fixing that by removing the return statement, the following works:

from textwrap import dedent

codeInString = dedent("""\
    sum = a + b
    print("sum =", sum)
""")
codeObject = compile(codeInString, 'sumstring', 'exec')

exec(codeObject, dict(a=5, b=6))  # -> sum = 11

Also note the the return value of exec() is None.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • thanks for help.. Yes I had tried this and it is working fine. But I am also stuck at another use case related to same problem. I have posted another question for that .. can you please help on it .. https://stackoverflow.com/questions/69151112/import-lib-not-working-with-exec-function – Nikhil Suthar Sep 12 '21 at 11:47
  • 1
    Nikk: Will take a look. – martineau Sep 12 '21 at 11:49