Default Value

Ian Kelly ian.g.kelly at gmail.com
Thu Jun 20 13:57:34 EDT 2013


On Thu, Jun 20, 2013 at 11:19 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Fri, Jun 21, 2013 at 3:12 AM, rusi <rustompmody at gmail.com> wrote:
>> Python (and all the other 'cool' languages) dont have gotchas because
>> someone malevolently put them there.
>> In most cases, the problem is seen too late and the cost of changing
>> entrenched code too great.
>> Or the problem is clear, the solution is not etc etc.
>
> Or, in many MANY cases, the choice was the right one, but isn't
> obvious to everyone.

I think it's worth pointing out that changing function defaults to
late-binding would merely change the nature of the gotcha, not eliminate it.

words = ("one", "two", "red", "blue", "fish")

def join_strings(strings=words):
    return ' '.join('%s %s' % (s, strings[-1]) for s in strings[:-1])

# Later:
words = open("gettysburg_address.txt", "r").read().split()
# Oops, the default argument of join_strings just changed.


Additionally, with late-binding semantics the default values would no
longer be default *values*.  They would be initialization code
instead, which sort of flies in the face of the idea that late-binding
would somehow be better for functional programming -- if the default
expressions have no side effects and since they don't depend on the
function arguments, why should they need to run more than once?  If
the goal is indeed to make the the functions more functional, then the
proper solution would be to keep the binding early but just disallow
mutable defaults altogether -- which is tricky to achieve in Python,
so we simply emulate it with the advice "don't use mutable function
defaults".



More information about the Python-list mailing list