What is a function parameter =[] for?

MRAB python at mrabarnett.plus.com
Wed Nov 18 20:02:11 EST 2015


On 2015-11-19 00:34, fl wrote:
> On Wednesday, November 18, 2015 at 7:15:05 PM UTC-5, Chris Angelico wrote:
>> On Thu, Nov 19, 2015 at 11:02 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>> > On Wed, Nov 18, 2015 at 4:22 PM, Chris Angelico <rosuav at gmail.com> wrote:
>> >> On Thu, Nov 19, 2015 at 10:14 AM, BartC <bc at freeuk.com> wrote:
>> >>> So, looking at some source code, a default value for certain types is only
>> >>> certain to be that value for the very first call of that function?
>> >>
>> >> On the contrary, it is certain always to be that exact object.
>> >
>> > "Certain" may be a bit overly strong.
>> >
>> >>>> def f(x=42):
>> > ...   return x
>> > ...
>> >>>> f()
>> > 42
>> >>>> f.__defaults__ = (43,)
>> >>>> f()
>> > 43
>>
>> I'll raise you one.
>>
>> >>> def f(x=42):
>> ...     return x
>> ...
>> >>> f()
>> 42
>> >>> import ctypes
>> >>> ctypes.c_int.from_address(id(43)+ ctypes.sizeof(ctypes.c_size_t) + ctypes.sizeof(ctypes.c_voidp)).value=42
>> >>> f.__defaults__ = (43,)
>> >>> f()
>> 42
>> >>>
>>
>> Nothing is certain in Python. And two wrongs can make a... hmm... no,
>> this is not a right. It is not a privilege either. It is a dastardly
>> trick played on people's minds.
>>
>> ChrisA
>
> After I try with
>
> list1 = eList(12, [2])
>
If you pass something into the parameter, the default isn't needed/used.

> and
>
> list1 = eList(12)
>
You're not passing anything into the parameter, so the default is used.

> it gives me new surprises. Even though I delete list1, the subsequent
> list1 = eList(12)
> will remember the number of '12' of the previous sequence. This is my new
> question: What does 'del' do? It does not look like a thorough list deletion
>   from the effect.
>
No, "del list1" doesn't delete the list, it deletes the name "list1".
The list still exists as the default parameter.

A default parameter is evaluated when the function is defined, and that
value exists as the default as long as the function exists.

If the value is mutable (can be modified), and you modify it, then the
function will see that modified value.




More information about the Python-list mailing list