473,748 Members | 10,649 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1456
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
1337
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 to fail for d.foo( ) c = myc()
4
2029
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 is that for some reason JS isn't receiving NULL for all the properties of the layer. For instance: HTML <div id="blarg">.....</div>
4
15619
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
4534
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
2280
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 such I need to be able to create the attribute with the version and some other values for the version. So I tried the following (typed for the example, not the actual code). defined the constructor for the Attrib as: public MyAttrib(params object...
4
1439
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
3441
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 "abc" only, and reflection ouotputs "def" and "abc" (in that order). Is there any way to get duplicated attributes to present themselves in the component model? Runnable demo code follows at foot. In context, I was looking to see if I could hang...
5
1437
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 set operations based on an attribute of the object, rather than the whole object. For instance, say I have (pseudo-code): LoTuples1 =
5
3993
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 custom method for my object?
0
8991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8830
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9541
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9370
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9247
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.