0

I was just trying out the exec() function in Python when I encountered an issue with my code. Here's some sample code to illustrate my issue:

I have a simple function that just executes code that is given to the function:

def executeCode(pythonCode):
    exec(pythonCode)

I have 2 variables that contain code with similar functions:

pythonCode1 = """
import pandas as pd

# Create a DataFrame from a dictionary
data = {'Name': ['John', 'Emily', 'Mike', 'Lisa'],
        'Age': [25, 28, 30, 27],
        'City': ['New York', 'London', 'Paris', 'Tokyo']}

def f(data):
   print(pd.DataFrame(data))

# Display the DataFrame
f(data)
"""
pythonCode2 = """
import pandas as pd

# Create a DataFrame from a dictionary
data = {'Name': ['John', 'Emily', 'Mike', 'Lisa'],
        'Age': [25, 28, 30, 27],
        'City': ['New York', 'London', 'Paris', 'Tokyo']}
df = pd.DataFrame(data)

# Display the DataFrame
print(df)
"""

When I run executeCode with the 2 chunks of code, I get 2 different results.

Running executeCode(pythonCode1) gives an error:


Traceback (most recent call last):
  File "C:\pythonEnvironment\vite-project\test.py", line 38, in <module>
    executeCode(pythonCode1)
  File "C:\pythonEnvironment\vite-project\test.py", line 35, in executeCode
    exec(pythonCode)
  File "<string>", line 13, in <module>
  File "<string>", line 10, in f
NameError: name 'pd' is not defined. Did you mean: 'id'?

While running executeCode(pythonCode2) returns the correct result:

    Name  Age      City
0   John   25  New York
1  Emily   28    London
2   Mike   30     Paris
3   Lisa   27     Tokyo

Could someone explain why this happens? I think its related to how the scopes of the functions work, since pythonCode2 does not contain a function and it works. I've also ensured that pandas is installed.

coolbeans
  • 13
  • 2

0 Answers0