Derek Martin wrote: > I'd like to know if it's possible to code something in Python which > would be equivalent to the following C: > > [Assume bool is typedef'd to int, and TRUE and FALSE are #defined to 1 > and 0, respectively] > > ---- debug.c ---- > #include <stdio.h> > > bool DEBUG; > > void dprint(char *msg) > { > if (DEBUG){ > printf("DEBUG: %s", msg); > } > } > > ---- end of debug.c ---- > > The idea being that all modules of the program would "import" this > code via the header file: > > ---- debug.h ---- > extern bool DEBUG; > void dprint(char *msg); > ---- end of debug.h ---- > > I'm specifically trying to avoid having to create a debug object and > pass it around... All modules should have visibility into the state of > whether DEBUG is turned on or off, and be able to use dprint(). Can > Python do this? > > I tried creating debug.py as such: > > ---- debug.py ---- > DEBUG = True > def dprint(msg): > if DEBUG: > print("DEBUG: %s" % msg) > ---- end ---- > > Then in the modules that wanted to use it, I did: > > from debug import DEBUG, dprint >
So don't import it that way. Instead, do it this way: import debug Then us like this: debug.DEBUG = True and debug.dprint(...) Lots of other possibilities exist -- but this solves your specific first question. > But I got some weird behavior. The imported copy of DEBUG is > read-only; if you update it, the name DEBUG points to a different > object which the other modules can't see. After doing some reading of > the docs, this behavior is explained and understood (though obviously > not what I want). It just occured to me that I might be able to get > around that by using a setter function in the module itself... I'll > try this later. > > The other weird behavior was, once I changed the value of DEBUG, > dprint() started to behave oddly. No matter what I passed as an > argument (and no matter what I set the value of DEBUG to be), it > started printing the exact literal string: > > DEBUG: %s > > whenever it was called. It was as if the function couldn't see the > parameter msg, which was passed via the call. Most unexpected, and > definitely undesirable. > I don't believe it -- send your *actual* code, and we'll all have a look. Gary Herron > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list