473,385 Members | 1,673 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,385 software developers and data experts.

beginner, idomatic python 2

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!
Aug 24 '07 #1
11 1185
On Aug 23, 10:21 pm, "bambam" <da...@asdf.asdfwrote:
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:

DEVICE_DICT = {
'PSP': PSP.
'Power Supply': PWR,
# etc.
}

and your function would simply return DEVICE_DICT[device_type]()

Aug 24 '07 #2
bambam a écrit :
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.
Dan already answered to this. Just as a side note, and since you're
trying to be "idiomatic", Python's naming convention is to use all_lower
for functions, MixedCaps for classes (except - mostly for historical
reasons - the builtin types...), and ALL_LOWER for symbolic (pseudo)
constants.

def Device(DeviceType):
if DeviceType=='PSP':
return PSP()
elif DeviceType=="Power Supply"
return PWR()
etc...
Thanks!

Aug 24 '07 #3
Bruno Desthuilliers a écrit :
(snip)
and ALL_LOWER
That's 'ALL_UPPER', of course :(
for symbolic (pseudo)
constants.
Aug 24 '07 #4
trying to be "idiomatic"

....I hope that if a python programmer looks at my code it
won't be an excuse to discard it. Less of an issue with Python
than with C/C++, but since I'm just starting...

def device(DeviceType):
if DeviceType=='PSP':
return Psp()
elif DeviceType=="Power Supply"
return Pwr()

What about the parameter "DeviceType"?

Also, I see what you mean now, DEVICE_DICT is upper
case because it is a 'constant' -- I'd missed that point.

Steve.

"Bruno Desthuilliers" <br********************@wtf.websiteburo.oops.com >
wrote in message news:46*********************@news.free.fr...
bambam a écrit :
>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.

Dan already answered to this. Just as a side note, and since you're trying
to be "idiomatic", Python's naming convention is to use all_lower for
functions, MixedCaps for classes (except - mostly for historical reasons -
the builtin types...), and ALL_LOWER for symbolic (pseudo) constants.

>def Device(DeviceType):
if DeviceType=='PSP':
return PSP()
elif DeviceType=="Power Supply"
return PWR()
etc...
Thanks!

Aug 24 '07 #5
bambam a écrit :
>trying to be "idiomatic"

...I hope that if a python programmer looks at my code it
won't be an excuse to discard it.
Hopefully not - and nothing forces you into adopting the common
convention !-) But it's a fact that Python relies heavily on naming
conventions, and that it greatly helps readability.
Less of an issue with Python
than with C/C++, but since I'm just starting...

def device(DeviceType):
if DeviceType=='PSP':
return Psp()
elif DeviceType=="Power Supply"
return Pwr()

What about the parameter "DeviceType"?
DEVICE_TYPES = {
'PSP' : Psp,
'Power Supply' : Pwr,
}

def get_device(device_type):
cls = DEVICE_TYPES.get(device_type, None)
if cls is not None:
return cls()
# implicitly returns None, which may or not be a GoodThing(tm)

HTH
Aug 24 '07 #6
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?

Steve.


"Dan Bishop" <da*****@yahoo.comwrote in message
news:11**********************@e9g2000prf.googlegro ups.com...
On Aug 23, 10:21 pm, "bambam" <da...@asdf.asdfwrote:
>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:

DEVICE_DICT = {
'PSP': PSP.
'Power Supply': PWR,
# etc.
}

and your function would simply return DEVICE_DICT[device_type]()

Aug 27 '07 #7
bambam wrote:
[but he top-posted]
"Dan Bishop" <da*****@yahoo.comwrote in message
news:11**********************@e9g2000prf.googlegro ups.com...
>On Aug 23, 10:21 pm, "bambam" <da...@asdf.asdfwrote:
>>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:

DEVICE_DICT = {
'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
unnecessarily.

Just my $0.02, others will have different opinions.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Aug 27 '07 #8
bambam a écrit :

<OT>Steve, could you please stop top-posting ?-) TIA </OT>
"Dan Bishop" <da*****@yahoo.comwrote in message
news:11**********************@e9g2000prf.googlegro ups.com...
>On Aug 23, 10:21 pm, "bambam" <da...@asdf.asdfwrote:
>>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:

DEVICE_DICT = {
'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,
Almost, yes !-)
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
It is. Dicts are probably the central data structure in Python, and are
highly optimised. You'll find quite a lot of dict-based dispatch in
Python code.
because Python programmers
expect to use dictionaries for their lookup tables.
Indeed - that's what dictionnaries are for.
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?
While it's technically possible, I wouldn't advise such a design (which
looks pretty close to the Prototype pattern) unless you need to have
something *highly* extensible and customisable (and even then, there are
other - possibly better - ways, depending on the context). If the Device
taxonomy is stable and well defined, you're certainly
DoingTheSimplestThing (here, a dict-based dispatch encapsulated in a
factory function...).

As a side note, in Python, inheritance is mostly an implementation
detail, and should usually not be used for typing.

My 2 cents...
Aug 27 '07 #9
Thank you.

I'm glad to see that I don't need to choose between two
opposing viewpoints :~)

Steve.
Aug 31 '07 #10

"Bruno Desthuilliers" <br********************@wtf.websiteburo.oops.com >
wrote in message news:46*********************@news.free.fr...
>
As a side note, in Python, inheritance ...
... should usually not be used for typing.
:~(
I'm sorry, I don't even know what that means... The code I
have inherited from someone only a little more knowledgeable
than me, and is still full of development artifacts anyway.

The Pwr and Psp classes inherit from the Device class not
neccessarily because that is a Good Thing, more because
the development process led to them being thought of that
way. All devices have a mixture of common and differing
attributes.

What is 'typing'?

Steve.
Aug 31 '07 #11
bambam a écrit :
"Bruno Desthuilliers" <br********************@wtf.websiteburo.oops.com >
wrote in message news:46*********************@news.free.fr...
>As a side note, in Python, inheritance ...
... should usually not be used for typing.

:~(
I'm sorry, I don't even know what that means... The code I
have inherited from someone only a little more knowledgeable
than me, and is still full of development artifacts anyway.

The Pwr and Psp classes inherit from the Device class not
neccessarily because that is a Good Thing, more because
the development process led to them being thought of that
way. All devices have a mixture of common and differing
attributes.

What is 'typing'?
Mmm... Most CS experts don't really agree on this, and I'm certainly not
one (expert). So I won't even try to explain it by myself, and let you
google for "type system", "static typing", "dynamic typing", "duck
typing" etc...

Now what I meant here is that in Python, you don't have to make class B
inherit from class A to let you use an instance of B where an instance
of A was expected - all you need is that both objects share the set of
attributes and methods you're going to use. Inheritence is only useful
for sharing common code.

HTH
Aug 31 '07 #12

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

Similar topics

3
by: Art | last post by:
NEWBIE ALERT! Esteemed List Participants and Lurkers: (System: P-II 350, 192 meg, Win98 SE, Python 2.2.3, wxPythonWIN32-2.4.1.2-Py22.exe) I'm having a lot of fun getting started with Python...
1
by: sarmin | last post by:
Hi Gurus... I am using pythonwin to write the programming code and boa constructor to build the GUI... the GUI and the python code work fine when run through pythonwin platform... i m now...
9
by: Birgit Rahm | last post by:
Hello newsgroup, I am a beginner, so I am asking maybe immoderate questions. I want to delete a variable, after filling it with complex objects. How should I do it? e.g. AAA = AAA = Can I...
18
by: mitchellpal | last post by:
Hi guys, am learning c as a beginner language and am finding it rough especially with pointers and data files. What do you think, am i being too pessimistic or thats how it happens for a beginner?...
5
by: Minlar Ginger | last post by:
HIi all: I am a new beginner to python, would you like give me some advice on studying it? Welcome to list some book on python for me. Thanks a lot.
6
by: Qun Cao | last post by:
Hi Everyone, I am a beginner on cross language development. My problem at hand is to build a python interface for a C++ application built on top of a 3D game engine. The purpose of this python...
7
by: M_M | last post by:
Hi, I am looking for a simple text book to introduce 13 to 18 year olds to python programming. Suggestion? New to python.
0
by: smilyface | last post by:
Hello, I'm a beginner with python and I have a problem. I'm using Python 2.5 with PyWin32 on Windows Vista. I try to run this script Office2PDF
1
by: =?utf-8?q?C=C3=A9dric_Lucantis?= | last post by:
Le Wednesday 02 July 2008 01:16:30 Ben Keshet, vous avez écrit : If the file you're reading is not too big, you can use file.readlines() which read all the files and returns its content as a...
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.