Super-newbie syntax error question
Cliff Wells
logiplexsoftware at earthlink.net
Mon Apr 29 13:06:30 EDT 2002
On Sun, 28 Apr 2002 23:07:14 GMT
Charlie Wood wrote:
> I have some code that I've cobbled together, and have just introduced a
> syntax error. I've read through the docs, done lots of trial and error, and
> I'm left scratching my head. Any ideas?
>
> Here's the code:
>
> def endElement(self, name):
> if self._parent == "item":
> if name == "title":
> self._title = self._text
> elif name == "link":
> self._link = self._text
> elif name == "description":
> self._descr = self._text
> elif name == "category":
> self._category = self._text
> elif name == "item":
> if not self._list_started:
> self._out.write("\n")
> self._list_started = 1
>
> self._out.write('%s: %s\n%s\n%s\n\n' %
> (self._category, self._title, self._descr,
> self._link))
>
> f = file("/article.txt", "w")
> f.write('Category: %s\nTitle: %s\nDescription: %s\nLink: %s\n\n' %
> (self._category, self._title, self._descr, self._link))
> f.close()
>
> self._title = None
> self._link = None
> self._descr = ""
> self._category = ""
Other people have addressed your syntax error, but I'd like to point out that
you may want to use a dictionary rather than assigning to attributes as this
could shorten your code quite a bit:
class SomeClass(...):
def __init__(self, ...):
self._initAttribs()
...
def _initAttribs(self):
"""explicitly initialize dictionary since it isn't clear
whether all values will be set later"""
self.attribs = {
'category': '',
'description': '',
'title': None,
'link': None
}
...
def endElement(self, name):
if self._parent = "item":
if name != "item":
self.attribs[name] = self._text
else:
if not self._list_started:
self._out.write("\n")
self._list_started = 1
self._out.write('%(category)s:'
'%(title)s\n'
'%(description)s\n'
'%(link)s\n\n'
% self.attribs)
# unsure of the indentation level of this bit since it appears
# to be incorrect in your original code (also note using "open"
# rather than "file")
f = open("/article.txt", "w")
f.write('Category: %(category)s\n'
'Title: %(title)s\n'
'Description: %(description)s\n'
'Link: %(link)s\n\n'
% self.attribs)
f.close()
self._initAttribs()
Whether you can take this approach of course depends upon your particular
application, but whenever I see if/elif/else start to stretch out, I start
thinking "lookup table". Not only does it eliminate long if/elif/else
constructs, but you can use it in format strings as well, which I find to be a
bit clearer.
--
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308 (800) 735-0555 x308
More information about the Python-list
mailing list