1

I have written the below code string and trying to execute it through the exec method. This code is running fine when I run it with global mode only.

codeRule = """import math
def fun (n):
    data = n
    data = data * math.pi
    print(data)
    return data
dd = fun(n)"""
    
codeObejct = compile(codeRule, 'sumstring', 'exec')
exec(codeObejct, dict(n = 10))

But my use case needs dd value outside of exec so I have used the below parameter to get dd value inside another dataframe.

loc = {}
exec(codeObejct, dict(n = 10), loc)
dd = loc["dd"]

But as soon as I use local it starts giving me an error regarding Lib Import such as

File "<stdin>", line 1, in <module>
  File "sumstring", line 7, in <module>
  File "sumstring", line 4, in fun
NameError: name 'math' is not defined

Can someone please help to solve this problem?

I have checked the below question's answer but I don't know how to fit it in my use case.

Why doesn't an import in an exec in a function work?

martineau
  • 119,623
  • 25
  • 170
  • 301
Nikhil Suthar
  • 2,289
  • 1
  • 6
  • 24

2 Answers2

1

Finally, I got solution,

I was missing one point with exec. Below is the solution that I got and I hope it will work for my actual Use case

codeRule = """import math
def fun (n):
    data = n
    data = data * math.pi
    return data
"""
#export Function 
exec (codeRule, globals())

dd = fun(10)
dd
31.41592653589793
Nikhil Suthar
  • 2,289
  • 1
  • 6
  • 24
1

Your answer looks good. Here's another more-convoluted approach if you need a fallback for your use case:

codeRule = """\
import math

def fun(n):
    data = n
    data = data * math.pi
    return data

loc['dd'] = fun(n)
"""

codeObject = compile(codeRule, 'sumstring', 'exec')
loc = {}
exec(codeObject, dict(n=10, loc=loc))
print(f"{loc['dd']=}")  # -> loc['dd']=31.41592653589793
martineau
  • 119,623
  • 25
  • 170
  • 301
  • @Nikk: I'm curious, didn't your own answer work? – martineau Sep 13 '21 at 14:06
  • my answer working fine.. and I have deployed it on Prod as well. Since your answer also looks correct so I have marked your answer correct answer since I can't tick my own answer :) Stackoverflow things.. – Nikhil Suthar Sep 16 '21 at 08:53
  • 1
    Well, thank you very much for the gesture—however I believe you *can* accept your own answer. maybe after waiting a certain amount of time. IMO yours is the better of the two (I upvoted it). – martineau Sep 16 '21 at 09:20