I’m building a module where there are a whole lot of diverse objects which need to be controlled by several variables.
If this were C, I would pass the objects a pointer to the variable / object I want them to watch, have the application change the variable as it needs to, and the objects in the module would “see” the new value.
In module foo.py:
class foo(object):
def __init__(self, varToWatch):
self.varToWatch = varToWatch
def DoSomething(self):
print self.varToWatch
In application, bar.py:
import foo
x = "before"
y = foo.foo(x)
y.DoSomething()
x = "after"
y.DoSomething()
This doesn’t work, of course, because the original value of x (or a reference to the original value of x?) is stored in y. You get “before” “before”.
So, I try…
- Passing the name of a global, and referring to the global by name in foo. No go, because the global is in the application’s space, not in the module.
- Using a global in the foo namespace, but I don’t know how to address that space by variable name, and we’re currently doing import * from foo rather than import foo. Changing this would be painful.
- Make a dictionary in the module and pass the name of a key in the dictionary to the objects in the module. Manipulate the contents of the dictionary from the application. Basically, I’m defining a new global space and sticking variables in it. I see no reason it wouldn’t work, but it feels untidy to me. Is that just me being unfamiliar with Python?
I’m not finding the kind of beautiful solutions I’m used to seeing come easily with Python, so I suspect I’m missing something.
Suggestions?
TIA,
– Tim.
How about putting the control variables in a separate module — say,
settings— and doing a separateimport settings? You could then have your objects watchsettings.barandsettings.quuxwhile still doingfrom foo import *to clutter up your main namespace. 😉 You could also use a global object to store your settings, with mostly the same effect.Of course, with problems such as these, one must wonder whether restructuring things to do a
import foowouldn’t help things in the long run… Impossible to judge without knowing the problem, though, so I’ll leave this problem to you.