Best way to make a number of tests against an object('s attributes) with absence of switch statement?

Phillip B Oldham phillip.oldham at
Sat Jun 14 04:25:50 CEST 2008

What would be the optimal/pythonic way to subject an object to a
number of tests (based on the object's attributes) and redirect
program flow?

Say I had the following:

pets[0] = {'name': 'fluffy', 'species': 'cat', 'size': 'small'}
pets[1] = {'name': 'bruno', 'species': 'snake', 'size': 'small'}
pets[2] = {'name': 'rex', 'species': 'dog', 'size': 'large'}

What I'd like to do is loop through 'pets', and test each object. Some
of the tests I'd like to perform are:

Is the size 'small' and species not 'dog'?
Is the species 'cat' and name 'fluffy'?
Is the species not 'dog' or 'cat'?

In PHP I'd use a switch statement similar to the following:

foreach( $pets as $pet) {
switch(true) {
case ( $pet['size'] === 'small' && $pet['species'] !== 'dog' ):
// do something
// etc...

Now, I understand from a bit of googling that python doesn't have a
switch statement, and because of this people rely on python's
polymorphism. Thats great, but I've yet to come across a decent
example which make a "click".

Any thoughts on how to proceed?

More information about the Python-list mailing list