Is there a better way of doing this?
Duncan Booth
duncan.booth at invalid.invalid
Sun May 29 10:04:34 EDT 2005
Michael wrote:
> I'm fairly new at Python, and have the following code that works but
> isn't very concise, is there a better way of writing it?? It seems
> much more lengthy than python code i have read..... :-)
> (takes a C++ block and extracts the namespaces from it)
Yes, there is a better way to write the code, but I'm afraid that the
better way will be much longer rather than shorter. Your code is trying to
pick up a complete C++ block by counting the opening and closing braces,
but this will break as soon as you have a brace character inside a string
or a comment.
The better solution would be to use a full blown parser, or at least a
lexer which recognises comments and strings. There are several parsing
packages for Python, you might like to look at Ply
(http://www.dabeaz.com/ply/) since that comes with a sample lexer for Ansi
C, and if you added some extra keywords (such as namespace) you could then
just treat your input as a token stream.
More information about the Python-list
mailing list