I have this code (Reset.py) that works how I want it to unless I import it.
class Res(object):
defaults={}
class NoKey: pass
def __init__(self):
for key, values in defaults.items():
globals()[key]=values
def add_defaults(key, values):
Res.defaults[key]=value
def remove_defaults(key=NoKey, remove_all=False):
if remove_all:
Res.defaults={}
else:
del Res.defaults[key]
Without importing:
>>> a=54
>>> Res.add_default('a', 3)
>>> Res()
<__main__.Res object at 0x>
>>> a
3
>>> #great! :D
With importing:
>>> a=54
>>> Res.add_default('a', 3)
>>> Res()
<Reset.Res object at 0x>
>>> a
54
This must mean when it is imported it changes the globals() under Reset and not __main__. How can I fix this?
[Edited defaults to Res.defaults under remove_defaults (defaults was not a global variable).]
You don’t fix this: it isn’t broken. Mutating globals, especially implicitly mutating globals within another module’s namespace, is a very bad idea that leads to confusing, unmaintainable, untestable code.
Your design seems really confusing.
Resdoens’t really seem to be a class. Most of it’s methods aren’t methods at all (they aren’t mutating some state stored in self); the only one that is defined like a method is your__init__, which won’t work (defaultsshouldn’t be defined from the snippet given; the class namespace only looks up there during the original definition of the class. Do you have another thing, a global nameddefaults?) If you are trying to useResto group related stuff, don’t use a class for that; that’s what modules are for in Python.Perhaps you should post a question describing the problem you are solving. I suspect this code indicates a very suboptimal design.