[Tutor] Re: small problem with lists/tuples [evil test cases]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Sep 29 16:35:59 EDT 2003



> The following simple trick might work:
>
> >>> a = ([['data']])
> >>> a
> [['data']]
>
> >>> def unpack(target):
> .. 	tmp = str(target)
> .. 	tmp = tmp.replace('[','').replace(']','')
> .. 	tmp = tmp.replace('(','').replace(')','')
> .. 	return eval(tmp)
> ..

Hi Pan,

Unfortunately, the implementation above is a little unsafe.  It's not just
because of the call to 'eval()', but because it is too sensitive to the
contents of the target.  For example, the following input:

    s = [['this: [', 'is a]'], 'test']

will break unpack(): it doesn't distinguish between the '[' that is part
of a string vs the '[' that represents the real structure of the object.

Is this example evil?  Yup.  *grin* But it's the sort of thing that
unpack() should be able to handle.

I think that a string-handling approach to this is more trouble than it's
worth, and it might just be better to bite down and go with the approach
that deals with the list structure explicitely.

Good luck to you!




More information about the Tutor mailing list