beginner, idomatic python 2

Steve Holden steve at
Mon Aug 27 12:57:40 CEST 2007

bambam wrote:
[but he top-posted]
> "Dan Bishop" <danb_83 at> wrote in message 
> news:1187927388.173203.298660 at
>> On Aug 23, 10:21 pm, "bambam" <da... at asdf.asdf> wrote:
>>> Would someone like to suggest a replacement for this? This is a
>>> function that returns different kinds of similar objects, depending
>>> on what is asked for. PSP and PWR are classes.  I don't really
>>> want to re-write the calling code very much: I'm just wondering
>>> if the function can be replaced with some kind of OOP pattern.
>>> def Device(DeviceType):
>>>     if DeviceType=='PSP':
>>>         return PSP()
>>>     elif DeviceType=="Power Supply"
>>>         return PWR()
>>>     etc...
>>> Thanks!
>> Typically, you'd use a dictionary:
>>    'PSP': PSP.
>>    'Power Supply': PWR,
>>    # etc.
>> }
>> and your function would simply return DEVICE_DICT[device_type]()
 > Thank you. I didn't reply earlier because I was trying to get my
 > head around what you wrote, which was strange and foreign
 > to me.
 > It seems to me that the dictionary object you suggested is a
 > direct replacement for the function code, only more efficient
 > because the case table is internalised with a hash table, and
 > the original if/elif/else case table was unlikely to be implemented
 > as a hash table.
 > And presumably, it is idiomatic because Python programmers
 > expect to use dictionaries for their lookup tables.
 > You have answered a question I didn't know enough to ask :~)
 > --which is why I started with the general question, so I don't
 > feel too stupid about that --.
 > And now I wonder about the 'other' question. Should I consider
 > dynamically overriding the methods in my 'Device' class, instead
 > of creating separate classes for the Psp and Pwr devices?
 > I could create an object of the base Device class, and at init
 > I could make sure the methods were connected for a Psp or
 > a Pwr device. When (if ever) is that a good idea?
The fact that it's technically possible in Python doesn't mean it's 
always a good idea. I prefer to reserve that kind of behavior for when 
the effective behavior of an object needs to change after it's been 
created. Here you know at creation time which type you want, so it makes 
sense to me to create exactly that kind of object. Otherwise you are 
obscuring your program's structure by using dynamic type modification 

Just my $0.02, others will have different opinions.

Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd 
Skype: holdenweb
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

More information about the Python-list mailing list