On Mon, May 25, 2020 at 6:24 PM Dominik Vilsmeier <dominik.vilsme...@gmx.de>
wrote:

> On 25.05.20 17:29, Ricky Teachey wrote:
>
>
> On Mon, May 25, 2020, 6:49 AM Rob Cliffe via Python-ideas <
> python-ideas@python.org> wrote:
>
>>  (Possibly heretical) Thought:
>> ISTM that when the decision was made that arg default values should be
>> evaluated
>>         once, at function definition time,
>> rather than
>>         every time the function is called and the default needs to be
>> supplied
>> that that was the *wrong* decision.
>> There may have been what seemed good reasons for it at the time (can
>> anyone point me
>> to any relevant discussions, or is this too far back in the Python
>> primeval soup?).
>> But it is a constant surprise to newbies (and sometimes not-so-newbies).
>> As is attested to by the number of web pages on this topic.  (Many of
>> them defend
>> the status quo and explain that it's really quite logical - but why does
>> the status quo
>> *need* to be defended quite so vigorously?)
>>
>
>
> *First of all*: supplying a default object one time and having it start
> fresh at every call would *require copying the object*. But it is not
> clear what kind of copying of these default values should be done. The
> language doesn't inherently know how to arbitrarily make copies of every
> object; decisions have to be made to define what copying the object would
> MEAN in different contexts.
>
> It wouldn't copy the provided default, it would just reevaluate the
> expression.
>
Agreed, it would definitely reevaluate each time, there would be no copying
involved at any stage. And evaluating each time wouldn't be slow, it might
even be faster than the `if x is None` check. Although if *all* defaults
were changed to evaluate each time, that'd probably slow things down a
little.

A couple of examples where these kinds of semantics are needed:

logging.StreamHandler has:

```
    def __init__(self, stream=None):
        if stream is None:
            stream = sys.stderr
```

This doesn't use a normal default so that something can patch sys.stderr
(very common and useful) before instantiating the handler but after
importing logging.

The code:

```
if context is None:
    context = getcontext()
```

appears 44 times in _pydecimal.py, although I can't guarantee that all of
them could be replaced by one of these proposals.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/LUIFMUNFODXN72ZT3UX6UDSA54GK3BHH/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to