[Tutor] Why is it invalid syntax to have a particular dictionary value as an argument?
boB Stepp
robertvstepp at gmail.com
Wed Apr 8 04:16:23 CEST 2015
On Mon, Apr 6, 2015 at 2:42 PM, Dave Angel <davea at davea.name> wrote:
> On 04/06/2015 03:20 PM, Emile van Sebille wrote:
>>
>> On 4/6/2015 7:54 AM, boB Stepp wrote:
>>>
[...]
>>
>> Maybe this form helps:
>>
>> Python 2.7.6 (default, Mar 22 2014, 22:59:56)
>> [GCC 4.8.2] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>> >>> d = {'a':'123'}
>> >>> def func(s=d['a']):
>> ... print s
>> ...
>> >>> func()
>> 123
>>
>
> Only if you know that nobody is going to be changing d.
>
>>>> d = {"a":"123"}
>>>> def func(s=d["a"]):
> ... print s
> ...
>>>> d["a"] = "new value"
>>>> func()
> 123
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.
But once s *is* evaluated, it stores a reference to the original
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...
~(:>))
--
boB
More information about the Tutor
mailing list