473,378 Members | 1,482 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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

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
break;
// 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?
Jun 27 '08 #1
2 1436
On Jun 14, 12:25 pm, Phillip B Oldham <phillip.old...@gmail.com>
wrote:
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'}
I'd suggest that you have a Pet class, instead of using dicts.
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
break;
// 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?
A switch statement is "optimal" when a variable needs to be tested
against N known constant values ... a compiler can emit code that
takes O(1) time (or O(log(N)) if the constants are sparse) instead of
O(N).

However the way you are using switch, it can't be other than O(N) and
it is just syntactic lemon juice for not having (or not using) if ...
elif ... else.

Python version:

for pet in pets:
if pet.size == 'small' and pet.species != 'dog':
pet.feed() # class instances can have user-definable methods
# don't need "break" to escape from if statement
elif ..... etc ...

HTH,
John
Jun 27 '08 #2
Phillip B Oldham a écrit :
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
break;
// 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.
You could also put it the other way round : Python doesn't have a switch
statement because peoples use polymorphism !-)

(nb : not that my "reversed" statement is in any way more true than
yours - but the fact is that procedural switch statement vs OO
polymorphic dispatch is not such a new topic...)
Thats great, but I've yet to come across a decent
example which make a "click".

Any thoughts on how to proceed?
The braindead canonical OO solution would be to make a specific class
for each species each implementing it's own version of do_something().
The problem is that it would only dispatch on species, not other
attributes (size etc). Which is a inherent limitation of the canonical
OO type-based single dispatch mechanism.

A more elaborate canonical OO solution would be to use the visitor
pattern to overcome the single dispatch limitation.

A yet more elaborate (but way less canonical) solution is to use
predicate-based dispatch (cf Philip Eby's work).

Anyway, and while each dispatch mechanism (from basic branching to
complex predicate-based systems) has it's pros and cons, I'd first think
twice (or more) about whether my current dispatch problem has some
relative stability wrt/ the domain - IOW, it's structurally part of the
domain and won't change anytime soon - or if it's one of those ad-hoc
short-lived illogical "business rule" that is potentially subject to
unpredictable change any other day. Because the appropriate solution
really depends on this kind of considerations.

Now wrt/ your concrete example: truth is that, while expressed as a
switch statement, it's in fact really a if/elif/.../, since the
condition is not a constant (so you don't gain any performance gain from
using a switch). So the simplest translation in Python is to use an
if/elif/...
for pet in pets:
if pet['size'] == 'small' and pet['species'] !== 'dog':
// do something
elif (other complex condition):
// etc

Jun 27 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Dan Perl | last post by:
Here is some code to illustrate a problem that I have: import copy class myc: def __init__(self): self.myf=file('bar.txt',"w") def foo(self): self.myf.write('hello world!') # it's going...
4
by: Mike Clair | last post by:
Hey, I'm having an issue with CSS, JS and the DOM. It's gonna drive me batty. I am trying to access the properties of a layer in JS which have been initially set in an external CSS. The problem...
4
by: Soundneedle | last post by:
Does anyone have any code snips that retrieves a file's (txt, xl, etc) created, accessed, and modified date properties? I've searched this group and couldn't find anything simple.... TIA
2
by: Fabian | last post by:
Hi, I would like to iterate attributes of an object like foreach(attribute a in o.attributes) { ... } any way i can do that?
3
by: ThisBytes5 | last post by:
I am using an attribute on the properties of my object to help with parsing of data. The attribute will determine if the current property is to be populated based on the version of the data. As...
4
by: sashang | last post by:
Hi Say I have a class like the following class Test: i = 1 def geti(self): return self.i
2
by: Marc Gravell | last post by:
It appears that when using the component model (or the default implementation, at least), then any duplicated attributes (e.g. from properties) are dropped. In my test, component-model outputs...
5
by: TheSeeker | last post by:
Hi, I have run into something I would like to do, but am not sure how to code it up. I would like to perform 'set-like' operations (union, intersection, etc) on a set of objects, but have the...
5
by: laredotornado | last post by:
Hi, I have this alert statement alert(myObj); which when executed, alerts "", or something similar. Is there a way I can see a list of attributes and values instead or do I have to write a...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.