[Python-ideas] Dynamic code NOPing

Vinay Sajip vinay_sajip at yahoo.co.uk
Tue Dec 25 15:45:20 CET 2012


Rene Nejsum <rene at ...> writes:

> So doing:
> 
> if log.debug.enabled():
> 	log.debug( bla. bla. )
> 
> Add's 5-10% extra code lines, whereas if we could do:
> 
> log.debug( bla. bla )
> 
> at the same cost would save a lot of lines.

Bearing in mind that the first statement in the debug (and analogous methods) is
a check for the level, the only thing you gain by having the same check outside
the call is the cost of evaluating arguments. But you can also do this by
passing an arbitrary class as the message object, which lazily evaluates only
when needed. Contrived example:

class Message(object):
    def __init__(self, func, x, y): # params should be cheap to evaluate
        self.func = func
        self.x = x
        self.y = y

    def __str__(self):
        return str(self.func(self.x**self.y)) # expense is incurred here

logger.debug(Message(factorial, 2, 15))

With this setup, no if statements are needed in your code, and the expensive
computations only occur when required.

Regards,

Vinay Sajip




More information about the Python-ideas mailing list