Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I don't have any evidence for my theory, but I assume it is because arguments are processed mostly on the function side instead of the call site.

My assumption just makes sense when all the function really gets is "a list of positional arguments and a dict of keyword arguments" (ala `*args, **kwargs`) that is "deconstructed" to the named variables on the function side. Then the function never gets the default value passed and fills it in before executing the body. Therefore it needs some value to assign and that value is determined when parsing the function definition.

So effectively I want to say that I think instead of the default value being passed at the call site (which is how C++ for example does it by inserting the expression inplace of a specified value) it is filled in by the function before executing the body.

In the end this is just a guess, but that is my working hypothesis.

 help



Function definitions in Python are just statements that are executed. When you execute the "def" statement, the default values are evaluated.

You can try it in the REPL:

  >>> def f(foo=print("Executing def statement!")):
  ...   print("Executing function body.")
  ... 
  Executing def statement!
  >>> f()
  Executing function body.
There's a fairly straight-forward explanation of this in the documentation: https://docs.python.org/3/reference/compound_stmts.html#func...

"Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call."




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: