473,513 Members | 2,688 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

<dict>.setdefault()

Hi!

I just realized that <dict>.setdefault *always* executes the second
argument - even if it's not necessary, because the requested item in
the first argument exists.

This is not what I expected - why evaluate the second argument if it's
not needed? Also this can lead to side-effects!

Example:
a = {}
b = {}
a.setdefault(1,b.setdefault(1,1)) 1

'1' didn't exist in a - so I expect 'b.setdefault(1,1)' to be
evaluated. Great.
a.setdefault(1,b.setdefault(2,1)) 1

'1' existed, so it's not necessary to evaluate 'b.setdefault(2,1)'.
But:
b

{2: 1, 1: 1}

.... shows that it was executed!

So it's not equivalent to:

if 1not in a:
b.setdefault(2,1)

Is this really by design? If there's a complicated, expensive to
calculate/build 2nd argument (maybe a function call) then it's also
quite ineffective to evaluate it just to throw away...

Thanks!

Tino

Jul 18 '05 #1
5 4599
Tino Lange a écrit :
I just realized that <dict>.setdefault *always* executes the second
argument - even if it's not necessary, because the requested item in
the first argument exists.


Since setdefault is a method, this is coherent with Python's standard
behaviour: method and function arguments are always evaluated before the
method is called.

--
Alexandre Fayolle
LOGILAB, Paris (France).
http://www.logilab.com http://www.logilab.fr http://www.logilab.org
Développement logiciel avancé - Intelligence Artificielle - Formations
Jul 18 '05 #2
On Thu, 31 Jul 2003 16:54:46 +0000 (UTC), Alexandre Fayolle
<al*@fayauffre.org> wrote:
I just realized that <dict>.setdefault *always* executes the second
argument - even if it's not necessary, because the requested item in
the first argument exists.
method and function arguments are always evaluated before the
method is called.


Yep. You're right. Of course it's like that.
Anyway - that's not what I expected in the first thought.

It shows that less code is not always the best code...

Thanks!

Tino
Jul 18 '05 #3
On 31 Jul 2003 18:01:51 +0100, jj*@pobox.com (John J. Lee) wrote:
Because that's the way Python always does function calls?
Of course. From the consistency point of view... perfectly right!
(I thought that maybe because these are very special low-level methods
for built-in types, it might be different....)
Don't, then. :-) Use key in dict, or dict.has_key(key).


or the C-like style:
a[3] = a.get(1) or b.setdefault(4,1)


Thanks!

Tino

Jul 18 '05 #4
Tino Lange wrote:
I just realized that <dict>.setdefault *always* executes the second
argument - even if it's not necessary, because the requested item in
the first argument exists.

This is not what I expected - why evaluate the second argument if it's
not needed? Also this can lead to side-effects!


Because Python doesn't have macros or special forms that look like
functions. If you see something that looks like a function, it
evaluates all arguments before it calls the function. Always. Changing
this would cause confusion, not resolve it.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ There's a reason why we / Keep chasing morning
\__/ Sandra St. Victor
Jul 18 '05 #5
Quoth Tino Lange:
On 31 Jul 2003 18:01:51 +0100, jj*@pobox.com (John J. Lee) wrote:

[...]
Don't, then. :-) Use key in dict, or dict.has_key(key).


or the C-like style:
a[3] = a.get(1) or b.setdefault(4,1)
Be careful doing that -- it relies on all possible values for a[1]
being true. Consider:
a = {1: 0}
b = {}
a[3] = a.get(1) or b.setdefault(4, 1)
a {1: 0, 3: 1} b

{4: 1}

--
Steven Taschuk o- @
st******@telusplanet.net 7O )
" (

Jul 18 '05 #6

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

Similar topics

44
3283
by: seberino | last post by:
Tuples are defined with regards to parentheses ()'s as everyone knows. This causes confusion for 1 item tuples since (5) can be interpreted as a tuple OR as the number 5 in a mathematical expression such as x = (5) * (4+6). Wouldn't it have been better to define tuples with <>'s or {}'s or something else to avoid this confusion?? ...
4
1795
by: Andy Leszczynski | last post by:
watch this: http://www.turbogears.org.nyud.net:8090/docs/wiki20/20MinuteWiki.mov or read this: http://www.turbogears.org.nyud.net:8090/docs/wiki2 0/page4.html should not it be: 2 def save(self, pagename, data, submit, new): 3 hub.begin()
8
17719
by: Brian P | last post by:
I want to expose a property of Dictionary<string, MyAbstractClass>. I tried to do it this way: private Dictionary<string, MyChildClass> _dictionary; public Dictionary<string, MyAbstractClass> { get { return _dictionary; } //error: no implicit conversion. }
12
21310
by: Brett Romero | last post by:
If I want to take action on the Add event of a generic Dictionary, do I need to create a custom Dictionary and add an event handler for the Add() method? The dictionary is a public field on a custom control. Thanks, Brett
1
1316
by: Brian Richards | last post by:
I'm experiencing some wierd behavior with a Dictionary<T,U> class using foreach loops, such that the Key returned in the foreach is not contained in the dictionary. code: Dictionary<A, B> dict; ..... foreach(A key in dict.Keys) {
6
46159
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that expects a List<string>. I often do the following: <BEGIN CODE> List<stringkeyNameList = new List<string>(); foreach (string keyName in this.myDictionary.Keys)
7
57519
by: Andrew Robinson | last post by:
I have a method that needs to return either a Dictionary<k,vor a List<v> depending on input parameters and options to the method. 1. Is there any way to convert from a dictionary to a list without itterating through the entire collection and building up a list? 2. is there a common base class, collection or interface that can contain...
4
4285
by: bytecolor | last post by:
I'm trying to extract the text of the current line on the <<Modified>> event. It doesnt work if I delete a character. If I type 'abc' I get 'abc' in text_changed(). If I hit backspace I still get 'abc'. Backspace once more, I get 'ab'. So the callback is called before the text is changed. But only on a delete. Someone told me it has to do...
6
1802
by: daohuy.hua | last post by:
The context is that I have a C# class named MainModel which has a private Dictionary<string, FileStreammember named dict. I also have a property Dict to access to this member: public Dictionary<string, FileStreamDict { get { return this.dict; } } The problem with this implementation is that I only want to give
0
7178
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...
1
7125
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7543
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...
0
5703
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5102
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...
0
3252
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
1612
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 we have to send another system
1
813
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
470
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...

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.