Using these four files, all in the same directory:
splitter.py
#imagine this is a third-party library
SPLIT_CHAR = ','
class Splitter(object):
def __init__(self, s, split_char=None):
self.orig = s
if not split_char:
self.splitted = s.split(SPLIT_CHAR)
a.py
#this person makes the mistake of re-setting the global variable
#in splitter to get different behavior, instead of just passing
#in the extra argument
import splitter
splitter.SPLIT_CHAR = '|'
def go():
s1 = splitter.Splitter("a|b|c|d")
print s1.orig
print s1.splitted
b.py
#this person expects the default behavior (splitting commas)
from splitter import Splitter
def go():
s1 = Splitter('a,b,c,d')
print s1.orig
print s1.splitted
experiment.py
import a
import b
a.go() #this one sets the global var in splitter
b.go() #this one expects the default behavior
The output of experiment.py
will be:
a|b|c|d
['a', 'b', 'c', 'd'] #okay... everything is fine
a,b,c,d
['a,b,c,d'] #not what the programmer expected.. should be split on commas
Is there a way to prevent this result? In this case, maybe a.py
and b.py
are written by two different coworkers, yet A's code is affecting B. It can sometimes be useful to overwrite something in a module (e.g. monkeypatching), but in this case it's producing confusing behavior.
Is there some way to make a copy of the module or sandbox the execution so that a.py
can't overwrite values in splitter.py
and end up affecting b.py
?
Also, let's say instead of the simple a.py
and b.py
, we are running a hundred web apps under mod_python or something (sharing as much as possible to decrease memory), is there a way to prevent one rogue app from tinkering with a module and breaking all the other apps? Something like Google App Engine has this solved, of course :)