473,473 Members | 1,823 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

The pythonic approach

def thisReallyWorks(x):
if x == "6$":
return "$10 000"
else:
return x

# or maybe

investments = {"6$": "$10 000"}
def thisReallyWorks(x):
return investments.get(x, x)
--
Timo "WT" Virkkala

"In the battle between you and the world, bet on the world."
Jul 18 '05 #1
7 1359
Timo Virkkala wrote:
def thisReallyWorks(x):
if x == "6$":
return "$10 000"
else:
return x

# or maybe

investments = {"6$": "$10 000"}
def thisReallyWorks(x):
return investments.get(x, x)


I really hope this is a contrived example, because if
I ever saw something like this in real code I'd barf.

Nevertheless, solely for the particular example shown
above, I'd have to say (a) is much better. The (b)
approach is obscure and indirect. One has to pause and
realize that the .get(x, x) thing means that if x
doesn't exist as a key in the dictionary, it will
instead be returned as the actual result. Using
x as the input, the lookup key, and the default result
makes the whole thing look bizarre and ill-conceived.

(My gut tells me that if this were something that was
required in real code, it would actually be using an
existing dictionary (not one created with a single
entry just before the function) and the best code
would be an inline .get() rather than a function call,
and that x might not even be its own default, but
I can't imagine what real code this corresponds to
so that's all I have to say about that. :-)

-Peter
Jul 18 '05 #2
Peter Hansen wrote:
Timo Virkkala wrote:
def thisReallyWorks(x):
if x == "6$":
return "$10 000"
else:
return x

# or maybe

investments = {"6$": "$10 000"}
def thisReallyWorks(x):
return investments.get(x, x)


I really hope this is a contrived example, because if
I ever saw something like this in real code I'd barf.

[snip]

It was, very contrived. I just like writing (wannabe) funny replies to
spams... :) The idea in the second one was to be extensible. Yes, the dict
should be defined elsewhere, and yes, inline .get is (usually) better than
hiding it in a function.

Maybe I should just write real code and not bother with nonsense :)

--
Timo "WT" Virkkala

"In the battle between you and the world, bet on the world."
Jul 18 '05 #3
Peter Hansen <peter <at> engcorp.com> writes:
(My gut tells me that if this were something that was
required in real code, it would actually be using an
existing dictionary (not one created with a single
entry just before the function) and the best code
would be an inline .get() rather than a function call,
and that x might not even be its own default, but
I can't imagine what real code this corresponds to
so that's all I have to say about that.


I actually wrote code not too long ago that did make a call like .get(x, x).
I had a dictionary of word stems, e.g.
{"invention":"invent", "assistance":"assist", ...} read in from a file. For
the particular app, if there was no stem for a word, I wanted to get the word
back. I didn't have a function for it in my code, but I don't see why a
function like:

def getstem(self, word):
return self.stemdict.get(word, word)

would be so unreasonable.

I don't know why you would have to "pause to realize" that .get(x, x) returns
x as the default any more than you'd have to "pause to realize" that .get(x,
y) returns y as the default...

Steve

Jul 18 '05 #4
Steven Bethard wrote:
Peter Hansen <peter <at> engcorp.com> writes:
(My gut tells me that if this were something that was
required in real code, it would actually be using an
existing dictionary (not one created with a single
entry just before the function) and the best code
would be an inline .get() rather than a function call,
and that x might not even be its own default, but
I can't imagine what real code this corresponds to
so that's all I have to say about that.
I actually wrote code not too long ago that did make a call like .get(x, x).
I had a dictionary of word stems, e.g.
{"invention":"invent", "assistance":"assist", ...} read in from a file. For
the particular app, if there was no stem for a word, I wanted to get the word
back. I didn't have a function for it in my code, but I don't see why a
function like:

def getstem(self, word):
return self.stemdict.get(word, word)

would be so unreasonable.


It wouldn't be "so unreasonable". Furthermore, it's a valid
example with context that makes it understandable and therefore
easier to discuss. I also point out that it uses a dictionary
with much more in it than one item... And the function name
makes sense in the problem domain, helping one understand the
purpose of the function and, thus, the reason for that particular
code pattern. (Even so, I would tend to include a doc-string
or comment describing the basic algorithm, to let another
programmer more easily comprehend the approach taken.)
I don't know why you would have to "pause to realize" that .get(x, x) returns
x as the default any more than you'd have to "pause to realize" that .get(x,
y) returns y as the default...


Principle of least surprise. One rarely encounters .get(x, x)
and so, upon seeing it, at least in the context of the contrived
example (as opposed to in your own example), one might at first
think it was a mistake.

Personally, I'd use a regular lookup and catch the KeyError,
making it very explicit what the intent of the author was.
And that's the subject of the thread, after all: what is
the more pythonic approach. For me, it's the one that
leads to the least surprise and potential for confusion.
(For others, it quickly gets into discussions of which
approach is "faster", as we may shortly see. ;-)

-Peter
Jul 18 '05 #5
Steven Bethard <st************@gmail.com> wrote:
...
I actually wrote code not too long ago that did make a call like .get(x, x).
I consider somedict.get(x, x) a _frequent_ Python idiom!

translate_some_tags = dict(
application='literal',
foobar='barfoo',
whatever='somethingelse',
}

def translate_tag(tagName, attributes_dict):
if tagName == 'emphasis' and attributes.get('role')=='bold':
return 'bold'
else:
return translate_some_tags.get(tagName, tagName)

Isn't that a pretty frequent idiom when doing some minor massaging of
XML markup, for example? (Spare me the passionate defenses of XSLT
please... I'm happy to use XSLT when warranted, but a lot of the XML
processing I do, and I _do_ do a lot of that, is in
Python+pulldom...!-).
back. I didn't have a function for it in my code, but I don't see why a
function like:

def getstem(self, word):
return self.stemdict.get(word, word)

would be so unreasonable.


A very good idea! If tomorrow you need to specialcase something, based
e.g. on RE's, you stick those into getstem (just like I do in
translate_tag for the few cases where a tag's translation may depend on
its attributes), and Bob's your uncle. MUCH better than spreading calls
to get(word,word) all over the place!!!
Alex
Jul 18 '05 #6
Peter Hansen <pe***@engcorp.com> wrote:
...
code pattern. (Even so, I would tend to include a doc-string
or comment describing the basic algorithm, to let another
programmer more easily comprehend the approach taken.)
That's never wrong, of course.
Principle of least surprise. One rarely encounters .get(x, x)


Funny -- I encounter it SO often I consider it a basic idiom!!!
Alex
Jul 18 '05 #7
Alex Martelli wrote:
Peter Hansen <pe***@engcorp.com> wrote:
Principle of least surprise. One rarely encounters .get(x, x)


Funny -- I encounter it SO often I consider it a basic idiom!!!


I think if the example had been one like your XML massaging
example, it wouldn't have felt very out of place, even if
I haven't seen it very often. (I'm quite sure I've used
it myself, for the same "optional translation" characteristics,
but I guess I work in areas different enough that it hasn't
been frequent.)

-Peter
Jul 18 '05 #8

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

Similar topics

9
by: Tom Evans | last post by:
My basic question: If I have a specific interface which I know is going to be implemented by a number of classes, but there is no implementation commonality between them, what is the preferred...
1
by: asdf sdf | last post by:
i need some advice. i'm a back end programmer historically, but have been exploring python for webapps and enjoying it. i need to build some simple Win client-server or standalone apps. the...
12
by: Nickolay Kolev | last post by:
Hi all, I would like to find a more pythonic way of solving the following: Having a string consisting of letters only, find out the total sound score of the string. The sound score is...
15
by: Ville Vainio | last post by:
Pythonic Nirvana - towards a true Object Oriented Environment ============================================================= IPython (by Francois Pinard) recently (next release - changes are...
12
by: Thomas Lotze | last post by:
Hi, I'm trying to figure out what is the most pythonic way to interact with a generator. The task I'm trying to accomplish is writing a PDF tokenizer, and I want to implement it as a Python...
1
by: rh0dium | last post by:
Hi all, I need a cleaner ( and shorter ) way to to look in my home directory or any directory for a directory called modules. This is what I currently have - but it is really ugly. Some a few...
33
by: Gregory Petrosyan | last post by:
Buenos dias, amigos! I have to write _simple_ gui library, for embedding into game. My first attempt was to use XML: isn't it cute to describe ui in such a way: <window> <title>Hello...
26
by: Frank Samuelson | last post by:
I love Python, and it is one of my 2 favorite languages. I would suggest that Python steal some aspects of the S language. ------------------------------------------------------- 1. Currently...
11
by: Hussein B | last post by:
Hey, Well, as you all know by now, I'm learning Python :) One thing that is annoying my is the OOP in Python. Consider this code in Java: -- public class Car { private int speed; private...
0
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,...
0
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...
0
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,...
0
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...
1
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...
0
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...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.