views:

26

answers:

1

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).]

+2  A: 

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. Res doens'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 (defaults shouldn'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 named defaults?) If you are trying to use Res to 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.

Mike Graham
I just wanted to know if it was possible, but I see your point. Thank you.
what
The short answer is no, methods do not know from which module they are being called and, indeed, that very concept is difficult to precisely define.
Mike Graham