On 17/05/2011 19:02, Joe Leonardo 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?

If value is [], then value.__class__() is [], so value.__class__() !=
[] is False.

What you meant was:

    if value.__class__() != [] or value.__len__() != 19:
        print 'You must pass a list that contains 19 fields.'
    else:
        print 'YAY!'

although the Pythonic way to write it would be:

    if not isinstance(value, list) or len(value) != 19:
        print 'You must pass a list that contains 19 fields.'
    else:
        print 'YAY!'

or, even better:

    if isinstance(value, list) and len(value) == 19:
        print 'YAY!'
    else:
        print 'You must pass a list that contains 19 fields.'
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to