[BangPypers] An interesting beginner post at Stackoverflow
Anand Chitipothu
anandology at gmail.com
Wed Oct 21 08:49:31 CEST 2009
On Wed, Oct 21, 2009 at 12:05 PM, Sidharth Kuruvila
<sidharth.kuruvila at gmail.com> wrote:
> Hi,
>
> d = {"a":"Hello"}
>
> print d.setdefault("a", "blah")
>
> Even though the string blah is not being used an object has to be
> created to represent it. Even worse, you could put some complex
> expression in there expecting it to evaluate only if the key is
> missing.
Your explanation is correct for the case of expressions but not for
string "blah".
Literal strings are interned. Python maintains a dict of all literal
strings used in the code and all occurrences get the same object.
>>> id("hello")
600320
>>> id("hello")
600320
But if it is an expression, different object is created every time.
>>> id("he" + "llo")
600704
>>> id("he" + "llo")
600768
Anand
More information about the BangPypers
mailing list