Ned Hulton Ned Hulton - 5 months ago 9
Python Question

Python variable scope and execution

I am executing a python script:

exec(open("process.py").read(), globals())


Is it possible to make all variables set within "process.py" local to that particular file?

Answer

You could execute the file's contents in a new dict instead of this code's own globals:

with open("process.py") as f:
    exec(f.read(), {})

This is a weird way to structure a Python program, though. Usually, you'd organize your code into modules and functions instead of exec-ing files.