Movatterモバイル変換


[0]ホーム

URL:


[Python-ideas] Efficient debug logging

Stephan Houbenstephanh42 at gmail.com
Tue Feb 14 12:48:43 EST 2017


Seems slightly simpler to just make debugLog accept a callable as analternative to a string.debugLog(lambda:( ‘info is %s’ % expensiveFunction()) )Op 14 feb. 2017 18:42 schreef "Kyle Lahnakoski" <klahnakoski at mozilla.com>:Can you wrap the expensive functions in lambdas? And have your loggerevaluate it, only if required?> debugLog( ‘info is %r’ % (lambda: expensiveFunction(),) )On 2017-02-14 10:51, Barry Scott wrote:> A common pattern I use is to have logging calls for debug and informationwith my applications.> The logging calls can be separately enabled and disabled.>> For example:>> debug_log_enabled = False> def debugLog( msg ):>       If debug_log_enabled:>             print( ‘Debug: %s’ % (msg,) )>> Then the caller can simple write:>> def main():>       debugLog( ‘Start of main’ )>> This is fine until the evaluation of the msg becomes expensive.>>       debugLog( ‘info is %r’ % (expensiveFunction(),) )>> What would be nice is to be able to avoid evaluation the tuple ofarguments if debug is> disabled as this can be expensive. I can write this:>>       if debug_log_enabled:  debugLog( ‘info is %r’ %(expensiveFunction(),) )>> But that is a more code then I would like to write. And if the debug codeis a performance problem cannot> be left in the production code.>> I could combine the boolean and the log function by using a class to tidyup the implementation.>> class DebugLog:>       def __init__( self, enabled = False ):>               self.enabled = enabled>>       def __bool__( self ):>               return self.enabled>>       def __call__( self, msg ):>               if self.enabled: print( ‘Debug: %s’ % (msg,) )>> And call like this:>>       dbg_log = DebugLog()>>        If dbg_log: dbg_log( ‘a debug message’ )>> But I’d like to only write:>>       dbg_log( ‘a debug message’ )>> And have the evaluation of the argument skipped unless its dbg_log isenabled.>> I cannot see how to do this with python as it stands.>> Something would have to be added to allow python to short circuit theargument tuple evaluation.>> Maybe python can check for a special dunder on the class that know how todo this idiom, __if_true_call__?>> Thoughts?>> Barry>> _______________________________________________> Python-ideas mailing list>Python-ideas at python.org>https://mail.python.org/mailman/listinfo/python-ideas> Code of Conduct:http://python.org/psf/codeofconduct/_______________________________________________Python-ideas mailing listPython-ideas at python.orghttps://mail.python.org/mailman/listinfo/python-ideasCode of Conduct:http://python.org/psf/codeofconduct/-------------- next part --------------An HTML attachment was scrubbed...URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170214/fef72c55/attachment.html>


More information about the Python-ideasmailing list

[8]ページ先頭

©2009-2026 Movatter.jp