any macro-like construct/technique/trick?

Andrew Dalke dalke at dalkescientific.com
Thu Jun 2 05:03:50 CEST 2005


Mac wrote:
> Is there a way to mimic the behaviour of C/C++'s preprocessor for
> macros?

There are no standard or commonly accepted ways of doing that.

You could do as Jordan Rastrick suggested and write your own sort
of preprocessor, or use an existing one.  With the new import
hooks you can probably make the conversion happen automatically,
though I hesitate suggestions that as you might actually do that.
It's typically a bad idea because you're in essence creating a
new language that is similar to but not Python, making it harder
for people to understand what's going on.

>  The problem: a lot of code like this:
> 
> def foo():
>     # .... do some stuff
>     if debug:
>         emit_dbg_obj(DbgObjFoo(a,b,c))
  ...
> * the two-lines of debug conditional tend to really break up the flow
> of the surrounding code

If flow is your only concern you can have a do-nothing
function and at the top have

if debug:
  emit = emit_dbg_obj
else:
  def emit(*args, **kwargs): pass

then write all your code as

   emit(DbgObjFoo(a,b,c))

> * using
>    def debug_emit(obj):
>        if debug:
>            emit_dbg_obj(obj)
> is a poor solution, because it *always* instantiates DbgObj*, even when
> not needed; I want to avoid such unnecessary waste

That would work as well of course.

How bad is the waste?  Is it really a problem?

Is all your code of the form

  emit(Class(constructor, args))

?  If so, your debug_emit could be made to look like

  debug_emit(klass, *args, **kwargs):
    if debug:
      emit_dbg_obj(klass(*args, **kwargs))

and used

  debug_emit(DbgObjFoo, a, b, c)
  debug_emit(DbgObjBar, d, e)

though I would use the do-nothing function version I sketched
earlier because, *ahem*, it avoids an unnecessary waste of
the extra "if debug:" check.  :)

				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list