Strange (?) list comprehension behavior

George Henry upandrunning247 at hotmail.com
Sat Jul 19 17:59:08 EDT 2003


I am a Python newbie, using IDLE, writing a lexical analyzer for a small 
expression language in Python 2.2.3.

class PSILex:
  ops = ["~", "!", "@", ... "|", "||", ... ]
  ...
  def __findAtom(self):
    result = ""
    ops = [op for op in PSILex.ops if self.text.startswith(op)]

... results in a traceback and "TypeError: expected a character buffer 
object." In trying to figure out what was going on, in the Python Shell I 
subsequently tried

>>>[op for op in PSILex.ops if "|| hello".startswith(op)]

with the same result. Printing type(self.text) immediately prior ot the 
above line proves that that attribute's type has not been compromised, so 
the problem appears to be with 'op'.

>>>[op for op in PSILex.ops if op.startswith("|| hello")]

yields "AttributeError: 'int' object has no attribute 'startswith'," 
however:

>>>[type(op) for op in PSILex.ops]

produces a list of <type 'str'> objects, as would be expected. So, what is 
op? Is it a string, an int, or something else? It appears that the 
interpreter may be confused. I persuaded the interpreter to cooperate by 
injecting an explicit evaluation of type(op):

        ops = [op for op in PSILex.ops if type(op) == type("") and \
               self.text.startswith(op)]

and this does what I want, and what I would expect without 'type(op) == 
type("") and '.

Can someone explain what is happening here? Or should I send my code to 
ww.python.org as a "defect report?"

Regards,
George

_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online  
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963






More information about the Python-list mailing list