[Tutor] pointer puzzlement
Dave Angel
davea at davea.name
Fri May 8 01:51:42 CEST 2015
On 05/07/2015 04:54 PM, Jim Mooney Py3.4.3winXP wrote:
> On 7 May 2015 at 13:03, Emile van Sebille <emile at fenx.com> wrote:
>
>> Compare to:
>>
>> def testid(K=1000000):
>> K += 10
>> return 'the ID is', id(K), K
>>
>
> Ah, thanks. I forgot small integers are saved in a table. I was looking at
> a demo that pointers to defaults in function parameters are persistent.
Python doesn't have pointers, and nothing here is persistent.
Persistence refers to a value surviving multiple invocations of a program.
> It
> used lists so I tried ints. Although I realized persistence also works for
> dicts ;')
>
> def testid(newitem, K={}):
> K[newitem] = newitem + 'item'
> return 'the ID is', id(K), K
>
>>>> testid('bonk')
> ('the ID is', 18263656, {'bonk': 'bonkitem'})
>>>> testid('clonk')
> ('the ID is', 18263656, {'bonk': 'bonkitem', 'clonk': 'clonkitem'})
>>>> testid('spam')
> ('the ID is', 18263656, {'bonk': 'bonkitem', 'clonk': 'clonkitem', 'spam':
> 'spamitem'})
The object is not immutable, so it can change. Therefore the += does an
in-place change, and you keep the same id.
--
DaveA
More information about the Tutor
mailing list