string to list when the contents is a list

Wes James comptekki at gmail.com
Thu Feb 18 20:56:16 CET 2010


On Thu, Feb 18, 2010 at 12:32 PM, Wes James <comptekki at gmail.com> wrote:
> On Thu, Feb 18, 2010 at 8:18 AM, Tim Chase
> <python.list at 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



More information about the Python-list mailing list