Python equivalent for C module
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Oct 20 13:29:16 EDT 2008
Derek Martin a écrit :
> 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);
> }
> }
This should have been:
fprintf(STDERR, "DEBUG: %s", msg);
STDOUT is for *normal* program outputs. Debug informations, warnings,
and all verbosity should go to STDERR.
> ---- 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?
Yes, indeed.
> I tried creating debug.py as such:
>
> ---- debug.py ----
> DEBUG = True
> def dprint(msg):
> if DEBUG:
> print("DEBUG: %s" % msg)
> ---- end ----
Same remark : please use sys.stderr
> Then in the modules that wanted to use it, I did:
>
> from debug import DEBUG, dprint
> But I got some weird behavior. The imported copy
It's not a copy.
> of DEBUG is
> read-only;
It's not read-only.
> if you update it, the name DEBUG points to a different
> object which the other modules can't see.
Indeed : the way you imported it explicitely made it a (module) local name.
> 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...
Just use a fully qualified name, so you dont make DEBUG local:
import debug
print debug.DEBUG
debug.DEBUG = True
print debug.DEBUG
Now note that ALL_UPPER names are - by convention - considered
'constants'. If this is supposed to be altered, don't write it ALL_UPPER.
> 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 just fail to see how the code you posted could expose such a
behaviour. Please post actual code.
Also and FWIW, Python has a logging module in it's stdlib. Please use it
instead of any half-backed squared-wheel homegrown solution.
My 2 cents
More information about the Python-list
mailing list