On 04/07/2015 10:16 PM, boB Stepp wrote:
Despite Mark's warning, I feel I must see if I understand what is going on here.
Switching to Py 3.4 since I am now at home:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600
64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
d = {'a': '123'}
def func(s=d['a']):
print(s)
print(d['a'])
func()
123
123
d['a'] = 'new value'
func()
123
new value
I added an additional print to the function to show the dictionary
entry's behavior.
First, my current understanding is that this form of the function does
not object to the presence of d['a'] in its parameter list because s
is the real parameter, d['a'] is its default value, but s is not
actually evaluated until run time.
s is not evaluated till the print statement. s is *bound* at function
call time. And at that time it is either bound to the object passed by
the caller, or to the default object.
In a simple assignment statement:
a = b + 6
the expression on the right is evaluated. The name on the left is not
evaluated, it is bound to. So we say
"a is bound to the result of the expression b+6"
But once s *is* evaluated, it stores a reference to the original
s is bound to the expression ''default_object'', which is to say it
copies the same reference that the default object stored earlier. So it
is bound to '123'
object, '123'. Changing d['a'] outside the function to a new value
does not alter the fact that s is storing the very same reference to
'123'. After reassigning d['a'] to point to the new object 'new
value', a new call to func() shows s still referencing the original
object and d['a'] referencing the new object. Is my comprehension of
these details correct? If yes, this is why I must constantly remind
myself that identifiers store references to objects, and that some
objects are mutable and some aren't, and these Python facts of life
are constantly challenging my old FORTRAN <= 77 ways of thinking...
~(:>))
--
DaveA
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor