default argument value is mutable
jmp
jeanmichel at sequans.com
Fri Oct 7 10:09:19 EDT 2016
On 10/07/2016 03:45 PM, ast wrote:
>
> "jmp" <jeanmichel at sequans.com> a écrit dans le message de
> news:mailman.210.1475844513.30834.python-list at python.org...
>> On 10/07/2016 02:07 PM, ast wrote:
>>>
>>> "jmp" <jeanmichel at sequans.com> a écrit dans le message de
>>> news:mailman.209.1475841371.30834.python-list at python.org...
>>>> On 10/07/2016 01:38 PM, Daiyue Weng wrote:
>>>
>>>>
>>>> So the rule of thumb for default argument value is "No mutable"
>>>>
>>>> Cheers,
>>>
>>>
>>> It can be used to store some variables from one call of
>>> a function to an other one.
>>>
>>> def test( _store={'x':0}):
>>>
>>> x = _store['x']
>>> ..... do some stuff
>>> _store['x'] = x
>>
>> For personal dirty scripts, possibly, for all other situations, never.
>
> not so dirty in my opinion
You made a point, it's not that dirty, it's an "advanced technique" that
is often actually an error when you don't know what you're doing. See
the OP's code.
I'm in an environment where people use python as a tool more than an
effective powerful language to write complex applications. That's
probably why I'm bias on this issue and prefer the cautious approach.
>> Especially since there's nothing in the code above that cannot be
>> solved using standard idioms .
>
> Yes, putting _store dictionnary outside
>
> _store={'x':0}
>
> def test( ):
>
> x = _store['x']
> ..... do some stuff
> _store['x'] = x
>
>
> or using a global variable, but you pollute in both case
> the global scope unnecessary.
What about
def test():
if not hasattr(test, '_store'): test._store={'x':0}
test._store['x'] += 1
Neither you pollute the global namespace, nor you pollute the function
signature with implementation specifics.
jm
More information about the Python-list
mailing list