472,958 Members | 1,816 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,958 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 1176
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: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.