Variations about macro definition

2 views
Skip to first unread message

BBi

unread,
Nov 20, 2008, 10:17:29 AM11/20/08
to creoleparser
Hi,

I defined a macro fro my own usage, starting from the example given in
http://creoleparserwiki.appspot.com/pages/DivMacroExample .

I modified slightly this example so that it scales better and,
hopefully, is easier to understand.

1- stick to a unique signature for every macro function: some_macro
(arg, body, isblock)

2- use a dictionary to select the macro to fire. This allows to get
rid of the successive elif that are prone to errors.

3- have an explicit default when no macro name is matched.

This gives something like:


from creoleparser import core, dialects
import genshi.builder as bldr

def float_div(arg, body, isblock):
if (not body or not isblock) :
return None
side = arg.strip()
if side not in ('left','right'):
return None
contents = text2html.generate(body)
fragment = bldr.tag.div(contents, style='float:'+side)
return fragment

def center_div(unused_arg, body, unused_isblock):
if (not body) :
return None
contents = text2html.generate(body)
fragment = bldr.tag.div(contents, CLASS='centered')
return fragment

def noop_macro(arg, body, isblock):
return None

macros = {'float' : float_div,
'center' : center_div,
}

def macro_dispatch(macro_name, arg,body,isblock):
return (macros.get(macro_name, noop_macro))(arg, body, isblock)

dialect = dialects.Creole10(
use_additions=True,
no_wiki_monospace=False,
macro_func=macro_dispatch
)
text2html = core.Parser(dialect)


With this pattern, it is quite easy to add new macros, without risking
regressions.

Cheers,
bruno

shday

unread,
Nov 20, 2008, 1:29:23 PM11/20/08
to creoleparser
Hi Bruno,

This is a much nicer pattern than the if-elif one that I've been using
in my examples. I'll think about ways of building the idea into the
library code. Probably a MacroDispatch baseclass that has a __call__
method and 'macros' attribute (a dictionary).

Thanks,

Steve

P.S. In your code, you can replace CLASS with class_ . Genshi will
remove the trailing underscore.

BBi

unread,
Nov 20, 2008, 4:57:20 PM11/20/08
to creoleparser
Thanks. Genshi is rather big to swallow..
Reply all
Reply to author
Forward
0 new messages