[FRPythoneers] Riddle me this Batman

Keith Hellman kehellman at yahoo.com
Mon Nov 19 20:41:53 MST 2001


>>> def func( l=[], d={} ) :
	print d
	for i in l : d[i] = i
	return d

>>> func( [1,2,3,4] )
{}
{4: 4, 3: 3, 2: 2, 1: 1}
>>> func( [5,6,7,8,9] )
{4: 4, 3: 3, 2: 2, 1: 1}
{9: 9, 8: 8, 7: 7, 6: 6, 5: 5, 4: 4, 3: 3, 2: 2, 1: 1}
>>> 

I realize I'm still an essential newbie, but this really throws a curve ball at my whole
impression of Python.  Why, on the second invokation of func() is d already valued from the
previous result?  I would understand if I had passed func( [1,2,3,4], my_dict ), then func(
[5,..], mydict ) - in fact this is what I would have expected.  But d should be set to {} on each
call, shouldn't it?

Occasionally I run across some nuance of Python that takes me a couple hours to 'reconcile' in my
head - but eventually I'm able to do so - but I just do it for this.

* Why isn't d equated to {} on each call invokation?
* Since d is (I would assume) held in the local dictionary for the particular invokation call
frame, why is its post-func value retained?   I would have thought it would be tagged for GC, and
therefore not reused.

I would appreciate any and all explanations - thanks in advance.


=====
Keith E. Hellman
kehellman at yahoo.com

__________________________________________________
Do You Yahoo!?
Yahoo! GeoCities - quick and easy web site hosting, just $8.95/month.
http://geocities.yahoo.com/ps/info1



More information about the FRPythoneers mailing list