Bizarre method keyword-arg bug.
Paul Boddie
paul at boddie.org.uk
Mon Aug 18 07:07:14 EDT 2008
On 18 Aug, 12:20, Jasper <jas... at peak.org> wrote:
>
> Not surprising, as it's fairly non-standard. I'd even argue that
> calling them "default arguments" is a misnomer -- they're more akin to
> static variables.
Indeed, default parameter values are occasionally suggested for that
purpose, although it has often been said that one shouldn't really use
them for that, either because there are often superior alternatives to
static variables, or because (as at least claimed in years gone by)
the behaviour may change one day. I think the latter explanation has
little substance now, at least for implementations compatible with
CPython.
> It doesn't help that the solution to get the expected behavior
> involves adding boiler-plate code all over.
Yes, it's a case of avoiding the full extent of the feature because it
doesn't do what one might expect. Personally, I only really use None,
numbers and strings as defaults, with the boilerplate you mention in
the function to get the initialisation that would have been provided
by the defaults. There is, however, a useful pattern which arises from
such a conservative approach: adopting None as a default (or perhaps a
special value) means that one has a way of explicitly indicating that
the default is desired, rather than omitting a parameter - something
which may not always be convenient. The boilerplate then loads the
appropriate default which may be stored in a more convenient location:
as a module global or in a class or instance attribute.
Ultimately, I suppose one could enforce some kind of least surprising
"best practice" by limiting default parameter values to being literals
of immutable objects or names, as opposed to expressions, thus
eliminating some potential confusion. Perhaps the various static code
checking tools provide guidance on this matter.
Paul
More information about the Python-list
mailing list