best way to parse a function-call-like string?

Robert Kern robert.kern at gmail.com
Thu Feb 26 16:43:32 EST 2009


On 2009-02-26 15:29, mh at pixar.com wrote:
> I have some strings that look like function calls, e.g.
>
> 	"junkpkg.f1"
> 	"junkpkg.f1()"
> 	"junkpkg.f1('aaa')"
> 	"junkpkg.f1('aaa','bbb')"
> 	"junkpkg.f1('aaa','bbb','ccc')"
> 	"junkpkg.f1('aaa','with,comma')"
>
> and I need to split them into the function name and list of parms, e.g.
>
> 	"junkpkg.f1", []
> 	"junkpkg.f1", []
> 	"junkpkg.f1", ['aaa']
> 	"junkpkg.f1", ['aaa','bbb']
> 	"junkpkg.f1", ['aaa','bbb','ccc']
> 	"junkpkg.f1", ['aaa','with,comma']
>
> What's the best way to do this?  I would be interested in either
> of two approaches:
>
>     - a "real" way which comprehensively
>
>     - a quick-and-dirty way which handles most cases, so that I
>       can get my coding partner running quickly while I do the
>       "real" way.  will the csv module do the right thing for
>       the parm list?

Use the compiler module to generate an AST and walk it. That's the real 
way. For me, that would also be the quick way because I am familiar with 
the API, but it may take you a little bit of time to get used to it.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though 
it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list