473,398 Members | 2,343 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Is there a better way of doing this?

Hi,
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)

def ExtractNamespaces(data):
print("Extracting Namespaces")
p = re.compile( 'namespace (?P<name>[\w]*)[\n\t ]*{')

subNamespaces = []

newNS = p.search(data)
while( newNS ):
print "\t" + newNS.group("name")

OPCount = 1
Offset = newNS.end()
while(OPCount > 0):
if( data[Offset] == "}" ):
OPCount = OPCount -1;
elif( data[Offset] == "{" ):
OPCount = OPCount + 1;
Offset = Offset+1;

#Extract Data:
newNSData = data[newNS.end():Offset-1]
data = data[0:newNS.start()] + data[Offset:]
newNamespace = [newNS.group("name"), newNSData];
subNamespaces.append(newNamespace)

#Perform NewSearch
newNS = p.search(data)
return [subNamespaces,data]


Jul 19 '05 #1
6 1647
On Sat, 28 May 2005 13:24:19 +0000, Michael wrote:
Hi,
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)

Does it work? If Yes, then "if it works, don't fix it".

Is it fast enough? If Yes, then "don't optimise prematurely".

Does it do everything you need it to do? If Yes, then "know when to stop
programming".

Is it written in good Python style? If Yes, then "leave it alone".

The last one is the most difficult, because nobody agrees what good
Python style is. A lot of it depends on who is going to be reading your
code. Personally, I worry about folks who try to turn every piece of code
into a one-liner. If you want to write perl, write perl. Just because you
can write something as a nested list comprehension doesn't mean you should.

Having said that, I'll make some stylistic suggestions:
def ExtractNamespaces(data):
print("Extracting Namespaces")
print is a statement, not a function. The brackets are syntactically
correct, but pointless. Remove them.
p = re.compile( 'namespace (?P<name>[\w]*)[\n\t ]*{')

subNamespaces = []

newNS = p.search(data)
while( newNS ):
Guido (our Benevolent Dictator For Life and creator of Python) hates
seeing whitespace next to parentheses. I agree with him. while(newNS)
good, while( newNS ) bad.

See http://www.python.org/doc/essays/styleguide.html for Guido's
suggestions.
print "\t" + newNS.group("name")

OPCount = 1
Offset = newNS.end()
while(OPCount > 0):
if( data[Offset] == "}" ):
See above comment about whitespace inside brackets.

More importantly, you don't need the brackets at all. You can write:

if data[Offset] == "}":

which is less visually confusing. The only time I use brackets in an if
statement is to clarify complex Boolean expressions, eg

if myFlag and ((somevalue == 3) or (num_fibberts != 1)):

Otherwise, drop the brackets.
OPCount = OPCount -1;
You aren't writing Pascal or C now, so you don't need the semi-colon. The
semi-colon isn't wrong, as such, since Python allows you to put multiple
statements on a single line separated with semi-colons, but it isn't
recommended and will give away the fact that you are (1) a newbie and (2)
not really comfortable with Python.

In more recent versions of Python, you can also write that as OPCount -= 1
elif( data[Offset] == "{" ):
OPCount = OPCount + 1;
Offset = Offset+1;
Again, drop the brackets from the elif statement and the semi-colons. Not
the colons, they are required!
#Extract Data:
More comments! Comments are good. There are those who claim that you
should write more comments than code. I don't quite agree with that, but
more detailed comments would not go astray.
newNSData = data[newNS.end():Offset-1]
data = data[0:newNS.start()] + data[Offset:]
newNamespace = [newNS.group("name"), newNSData];
subNamespaces.append(newNamespace)
By now you should be sick of me telling you not to use semi-colons.
#Perform NewSearch
newNS = p.search(data)
return [subNamespaces,data]


A single space after commas helps make the phrase more readable.

Other than those stylistic comments, and the need for more comments, it
looks good to me.
--
Steven
Jul 19 '05 #2
Steven D'Aprano wrote:
Guido (our Benevolent Dictator For Life and creator of Python) hates
seeing whitespace next to parentheses. I agree with him. while(newNS)
good, while( newNS ) bad.


while is a statement, so while(newNS) is bad in more than one way.

</F>

Jul 19 '05 #3
On 5/29/05, Cyril BAZIN <cy*********@gmail.com> wrote:
Hi,

I don't know very well what you want to do, but if you want to parse c++,
take a look at "GCC-XML python" (http://www.gccxml.org) and the python
binding (http://pygccxml.sourceforge.net/). These tools
translate c++ code to XML. Then, you can parse xml with your favorite tools
and find the namespaces for example...


Small correction: pygccxml does not translate C++ to xml. The purpose
of pygccxml is to read file generated by GCC-XML and provide simple
framework to navigate C++ declarations using python classes.

Roman
Jul 19 '05 #4
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.

Jul 19 '05 #5
Steven D'Aprano wrote:
print is a statement, not a function. The brackets are syntactically
correct, but pointless. Remove them. .... On Sat, 28 May 2005 13:24:19 +0000, Michael wrote:
while( newNS ):


Guido (our Benevolent Dictator For Life and creator of Python) hates
seeing whitespace next to parentheses. I agree with him. while(newNS)
good, while( newNS ) bad.


while is a statement, not a function. The brackets are syntactically
correct, but pointless. Remove them. ;^)

while newNS:

Not only are they pointless (in both print and while), but they are
blurring the distinction between statements and callables, and they
add noise. Only wrap the expression following a statement such as
while, if, print etc in () if the following expression spans several
lines.

Using () instead of \ as line continuator is considered good style.
(See http://www.python.org/doc/essays/ppt...honRegrets.pdf
slide 3.) In that case, make sure you have a space between the
statement and the (. Never have space between a callable and
the (. That way, we emphasize the difference between a statemens
and a call. E.g:

while (aVeryVeryVeryLongVariableName == anotherVeryVeryLongName
or aThirdLongVariableName == aFourthLongVariableName):
something = function(parameterOne, parameterTwo, parameterThree,
parameterFour, parameterFive, etc)
N.B. Use "while (" but "function(".

(I'm not suggesting that such long variable names are generally
good, but there are certainly cases where both logical expressions
and parameter lists will be too long for one line, for instance when
working with stuff such as the win32 APIs.)

Please note the big conceptual difference in using a statement which
controls local program flow, and calling a function/method/class etc
which means that we transfer control to a different part of the
program. Some of the current statements in Python, e.g. print,
actually behaves more like a function than like the normal statements,
and this might be considered a wart. It's also mentioned in Guido's
"regrets" slides mentioned above. Print and exec *are* still not
callables though. They *are* statements, whether we like it or not.

If writing "print(something)" feels better than "print something",
I suggest you define a function called writeln etc and use that
instead of print, e.g.
import sys
def writeln(*args):

.... sys.stdout.write(" ".join(map(str, args)) + '\n')
Jul 19 '05 #6
On Mon, 30 May 2005 14:05:36 +0200, Magnus Lycka wrote:
Steven D'Aprano wrote:
> print is a statement, not a function. The brackets are syntactically
> correct, but pointless. Remove them. ...
On Sat, 28 May 2005 13:24:19 +0000, Michael wrote:
while( newNS ):


Guido (our Benevolent Dictator For Life and creator of Python) hates
seeing whitespace next to parentheses. I agree with him. while(newNS)
good, while( newNS ) bad.


while is a statement, not a function. The brackets are syntactically
correct, but pointless. Remove them. ;^)


Um. Er.

Of course I knew that. I deliberately made that error to see if others
were paying attention. Well done, go to the head of the class. *cough*

:-)

while newNS:

Not only are they pointless (in both print and while), but they are
blurring the distinction between statements and callables, and they
add noise. Only wrap the expression following a statement such as
while, if, print etc in () if the following expression spans several
lines.


Yes, of course you are right. Serves me right for replying to Usenet posts
in the wee hours of the morning.

Although, pardon me for stating the obvious, using brackets for
precedence, or to add clarity by careful grouping, is always allowed even
if the expression doesn't span more than one line.

eg while (index > 0) and (not found or still_working):
--
Steven.
Jul 19 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Michele Simionato | last post by:
I often feel the need to extend the string method ".endswith" to tuple arguments, in such a way to automatically check for multiple endings. For instance, here is a typical use case: if...
220
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have...
3
by: ina | last post by:
I want to walk a folder structor and group all the files by extention. Here is the code I put together is there a better way of doing this? <code> import os folderKey = "Folders" dicExt = {}...
19
by: James Fortune | last post by:
I have a lot of respect for David Fenton and Allen Browne, but I don't understand why people who know how to write code to completely replace a front end do not write something that will automate...
43
by: Rob R. Ainscough | last post by:
I realize I'm learning web development and there is a STEEP learning curve, but so far I've had to learn: HTML XML JavaScript ASP.NET using VB.NET ..NET Framework ADO.NET SSL
22
by: JoeC | last post by:
I am working on another game project and it is comming along. It is an improvment over a previous version I wrote. I am trying to write better programs and often wonder how to get better at...
19
by: Mary Pegg | last post by:
There's got to be a better way: if (isset($c)) echo $c."<br>"; if (isset($c)) echo $c."<br>"; if (isset($c)) echo $c."<br>"; if (isset($c)) echo $c."<br>"; if (isset($c)) echo $c."<br>"; but...
34
by: pamela fluente | last post by:
I would like to hear your *opinion and advice* on best programming practice under .NET. Given that several time we cannot change: MyCollection.Clear into the instantiation of a NEW...
20
by: mike3 | last post by:
Hi. (Xposted to both comp.lang.c++ and comp.programming since I've got questions related to both C++ language and general programming) I've got the following C++ code. The first routine runs in...
13
by: Marco Bizzarri | last post by:
Sorry... pressed enter but really didn't want to. As I said, let's say I have a class class A: def __init__(self): self.x = None
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.