Re: if not DEBUG: log = null_log
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: if not DEBUG: log = null_log

From: Bengt Richter <bokr@oz.net>
Date: Wed Jul 13 2005 - 04:25:35 CEST

On Wed, 13 Jul 2005 11:00:14 +1000, Simon Burton <simon@arrowtheory.com> wrote:

>
>Hi,
>
>I'm after a no-op command, so that i can redirect
>logging commands in performance critical code.
>
>Something like this:
>
>def log(*args): print args
>def null_log(*args): pass
>if not DEBUG: log = null_log
>
>is unacceptable because of the overhead of calling
>functions in python.
>
I think you could make the existence of log calls dependent on
whether you compile with an optimize flag by abusing
an assert statement, e.g.,

    assert log(some, args) or True

would always make the call in debug mode, but would never raise the exception
because of the "or True", even if log return None. If you compile with optimization,
the entire assert statement disappears from the byte code, UIAM.

if you use

    if __debug__: log(some, args)

I think[1] you still the the if-test code, though that is pretty quick
compared to a function call, so maybe you don't have to worry about it,
unless it is in a super-hot loop.

[1] I thought is saw somewhere that
    if __debug__: suite
might be completely optimized away like assert, but I couldn't locate it off hand.
It would seem pretty safe and useful though.

Regards,
Bengt Richter
Received on Thu Sep 29 16:55:13 2005