Isolated environment for execfile
Lie Ryan
lie.1296 at gmail.com
Wed Oct 1 13:40:50 EDT 2008
On Wed, 01 Oct 2008 11:11:29 +0000, Igor Kaplan wrote:
> Hello python gurus.
>
> I got quite unusual problem and all my searches to find the answer on
> my
> own were not successful.
> Here is the scenario:
> I have the python program, let's call it script1.py, this program
> needs to
> execute another python script, let's call it script2.py.
> In script1.py I have the statement:
> execfile('script2.py')
> Everything is fine beside one thing. The script2.py is pretty big
> python
> program which does a lot of things and also while runs, it modifies many
> variables and module members, such for example as sys.path. So when
> script2.py exits all changes which it does are visible in my main
> program, script1.py. Even more, I need to execute script2.py in loop,
> several times during script1.py session. And all changes, which
> script2.py does just accumulate.
>
> I wander, is there any way to execute script2.py in it's own
> environment,
> so when script2.py exits, all modifications, which it is done in global
> modules are gone?
> Ideally I would love to have the following.
(snip)
> Thanks in advance.
>
> Igor.
I smelled a really strong sign of bad code.
1. In python, functional style programming is very much preferred. In
short, functional style programming requires that: a function never makes
a side-effect (python doesn't enforce this[1] as python is not a pure
functional language).
2. In any programming language, the use of global variable must be
minimized, and modifying global is even more frowned upon.
Aside:
If you need an isolated environment, it is probably much better if you
use class. Each instance of a class lives separately, independent to each
other.
e.g.:
class Test(object):
def func(self, n):
self.n = n
a = Test()
b = Test()
a.func(10)
b.func(20)
print a.n # 10
print b.n # 20
[1] in fact, many built-in standard library do use side-effects, and OOP-
style programming (more appropriately Java-style OOP) relies heavily on
side-effect.
More information about the Python-list
mailing list