PyWart: The problem with "print"

Chris Angelico rosuav at gmail.com
Sun Jun 2 13:20:52 EDT 2013


On Mon, Jun 3, 2013 at 3:04 AM, Rick Johnson
<rantingrickjohnson at gmail.com> wrote:
>  * Woefully inadequate because: Switching on or off the debug
>    messages is only valid in the current module that the
>    function was imported. What if you want to kill all
>    debugprint messages EVERYWHERE? Do you really want to edit
>    "debug = BOOLEAN" in every source file OR do something
>    stupid like import debugprint and edit the DEBUG constant
>    OR even dumber, edit the debugprint source code? GAWD NO!

Easy fix to this one. Instead of copying and pasting debugprint into
everything, have it in a module and import it everywhere. Then the
debug flag will be common to them all.

Oh, and you probably want to add **kwargs to debugprint, because the
print function does a lot more than sys.stdout.write does:

>>> print(1,2,3,4,sep='#')
1#2#3#4

>  * But even if you are willing to cope with all the "switch-
>    on-and-off" nonsense, are you willing to have you code
>    slowed by numerous calls to a dead function containing a
>    comparison that will always be false?

Hmm. Could be costly. Hey, you know, Python has something for testing that.

>>> timeit.timeit('debugprint("asdf")','def debugprint(*args):\n\tif not DEBUG: return\n\tprint(*args)\nDEBUG=False',number=1000000)
0.5838018519113444

That's roughly half a second for a million calls to debugprint().
That's a 580ns cost per call. Rather than fiddle with the language,
I'd rather just take this cost. Oh, and there's another way, too: If
you make the DEBUG flag have effect only on startup, you could write
your module thus:

if DEBUG:
  debugprint=print
else:
  def debugprint(*args,**kwargs):
    pass

So you can eliminate part of the cost there, if it matters to you. If
a half-microsecond cost is going to be significant to you, you
probably should be looking at improving other areas, maybe using
ctypes/cython, or possibly playing with the new preprocessor tricks
that have been being discussed recently. There's really no need to
change the language to solve one specific instance of this "problem".

ChrisA



More information about the Python-list mailing list