[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: string to list when the contents is a list

Wes James

2/18/2010 7:56:00 PM

On Thu, Feb 18, 2010 at 12:32 PM, Wes James <comptekki@gmail.com> wrote:
> On Thu, Feb 18, 2010 at 8:18 AM, Tim Chase
> <python.list@tim.thechases.com> wrote:
>> Wes James wrote:
> <snip>
>
>>
>> Just to add to the list of solutions I've seen, letting the built-in csv
>> module do the heavy lifting:
>>
>>  >>> s = "['a','b']"
>>  >>> import csv
>>  >>> no_brackets = s[1:-1] # s.strip(' \t[]')
>>  >>> c = csv.reader([no_brackets], quotechar="'")
>>  >>> c.next()
>>  ['a', 'b']


Hmm. When I put csv.reader in a class:

import csv

class IS_LIST():
def __init__(self, format='', error_message='must be a list!'):
self.format = format
self.error_message = error_message
def __call__(self, value):
try:
if value=='[]' or value=='':
value=[]
else:
no_brackets = value[1:-1] # s.strip(' \t[]')
c = csv.reader([no_brackets], quotechar="'")
value=c.next()
return (value, None)
except:
return (value, self.error_message)
def formatter(self, value):
return value

I get an error (when I take the "try" out):

AttributeError: 'function' object has no attribute 'reader'

Why?

-wes
1 Answer

aahz

2/18/2010 9:19:00 PM

0

In article <mailman.2736.1266522979.28905.python-list@python.org>,
Wes James <comptekki@gmail.com> wrote:
>
> try:
> if value=3D=3D'[]' or value=3D=3D'':
> value=3D[]
> else:
> no_brackets =3D value[1:-1] # s.strip(' \t[]')
> c =3D csv.reader([no_brackets], quotechar=3D"'")
> value=3Dc.next()
> return (value, None)
> except:
> return (value, self.error_message)

Two important points:

* Don't use bare except: clauses

* Put less code in the try: clause to make it easier to track down
problems
--
Aahz (aahz@pythoncraft.com) <*> http://www.python...

"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"