4 ms·
As Python is now, this code: def myfun(person = Person()): ... will evaluate `Person()` only once. If you want it to be evaluated every time, you have to
by justinpombrio 5y ago
As Python is now, this code:
def myfun(person = Person()): ...
will evaluate `Person()` only once. If you want it to be evaluated every time, you have to say:
def myfun(person = None):
if person is None: person = Person()
...
What's being suggested, is to change the language so that the default-arg code:
def myfun(person = Person()): ...
will evaluate `Person()` on every call. If you wanted it evaluated only once, you would have to say:
__default_person = Person()
def myfun(person = __default_person): ...
In either case, it's pretty easy to obtain the other case, and the question is what the best default is. My impression is that "evaluate every time" is both a lot less surprising and more commonly what you want, so it would be the better default.
- meowface 5y agoRight. They were saying they much prefer the current way over the proposed way. It makes sense if you realize that the function is defined once, and for the function need to be defined, its signature needs to be defined with it. Default arguments are part of the signature, not part of the function body. It would make sense to pass a callable without calling it, like def myfun(person = Person): ... but if the call occurs in the function signature, it doesn't really make sense that the call would somehow happen again and again. You're not defining a function in the signature; you're specifying a value right there. The current PEP proposal is to enable the "evaluate at function call time" ability with new syntax, which I think makes the most sense semantically and also doesn't break existing code.
- justinpombrio 5y ago> if the call occurs in the function signature, it doesn't really make sense that the call would somehow happen again and again. You're not defining a function in the signature; you're specifying a value right there. There are things besides functions and values! They're called "expressions" or "code blocks", and in an impure language like Python they can produce a different value each time you evaluate them. In my second example, "Person()" is neither a value nor a function -- it's an expression that would be evaluated each time the function is run. This isn't that weird; in `while condition: body`, `body` is a block that's evaluated multiple times. It would need to capture variables from the local environment though, which makes it more complicated to implement. > The current PEP proposal is to enable the "evaluate at function call time" ability with new syntax, which I think makes the most sense semantically and also doesn't break existing code. Oh yeah I wasn't suggesting breaking existing code. Just that if I was designing a language from scratch, it would probably avoid the Python foot-gun and have default arguments evaluated each time.