On Tue, May 17, 2011 at 12:02 PM, Joe Leonardo
<joe.leona...@datalogix.com>wrote:

> Hey all,
>
>
>
> Totally baffled by this…maybe I need a nap. Writing a small function to
> reject input that is not a list of 19 fields.
>
>
>
> def breakLine(value):
>
>     if value.__class__() != [] and value.__len__() != 19:
>
>         print 'You must pass a list that contains 19 fields.'
>
>     else:
>
>         print 'YAY!'
>
>
>
> If I pass:
>
> breakLine([])
>
>
>
> I get:
>
> YAY!
>
>
>
> I expect:
>
> You must pass a list that contains 19 fields.
>
>
>
> If I print len(value) I get: 0
>
>
>
> What is going on here?
>
>
Evaluating the conditions, the first line reduces to "if False and True"
which further reduces to "if False".  You probably meant to write "or"
instead of "and".

A few other comments:

"value.__len__()" is better written as "len(value)".

"value.__class__() != []" would be better written as "type(value) is list".

Better yet would be to not worry so much about the particular type of
sequence passed in by the caller.  To allow any sequence you could just do
this:

def break_line(value):
  if len(value) != 19:
    raise ValueError('value must contain 19 items')

If value is not a sequence, then it will just raise a TypeError, which is
typically what you would want in that situation anyway.  Or if value
absolutely must be a list due to the way your function works, you can do
this:

def break_line(value):
  value = list(value)
  if len(value) != 19:
    raise ValueError('value must contain 19 items')

Again that will just raise a TypeError if the value can't be converted to a
list.  One of the niceties about this version is that value can be any
iterable, not just a sequence.

Cheers,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to