any macro-like construct/technique/trick?

Kay Schluehr kay.schluehr at gmx.net
Sun Jun 5 10:36:43 EDT 2005



Mac wrote:
> Is there a way to mimic the behaviour of C/C++'s preprocessor for
> macros?  The problem: a lot of code like this:
>
> def foo():
>     # .... do some stuff
>     if debug:
>         emit_dbg_obj(DbgObjFoo(a,b,c))
>
>     # .... do more stuff
>     if debug:
>         emit_dbg_obj(DbgObjBar(d,e))
>
>     # ... and so on ...
>
> Notes:
>
> * the two-lines of debug conditional tend to really break up the flow
> of the surrounding code
>
> * in C you could wrap them with a macro so you could do
> DEBUG_EMIT(DbgObjFoo(a,b,c)), etc, with the macro only instantiating
> the object and processing it if the debug flag was set.  The one-liner
> is MUCH less disruptive visually when reading code

Make emit_dbg_obj() a class to create one-liners:

class Emit_dbg_obj:
    debug = True
    def __init__(self, algo):
        self.algo = algo

    def call_if_debug(self):
        if self.debug:
            return self.algo

def foo2():
    # .... do some stuff
    Emit_dbg_obj(DbgObjFoo(a,b,c)).call_if_debug()

    # .... do more stuff
    Emit_dbg_obj(DbgObjFoo(c,d)).call_if_debug()


Ciao,
Kay




More information about the Python-list mailing list