Default parameter for a method

George Sakkis george.sakkis at gmail.com
Thu Apr 17 00:00:58 EDT 2008


On Apr 16, 4:21 pm, John Nagle <na... at animats.com> wrote:

> In general, default values should be immutable constants only.

This is more restrictive than necessary; it should rather read "In
general, default values should be *treated as* immutable objects
only". It's perfectly fine for a default value to be mutable if the
function doesn't modify it, as in the following example:

def parse(text, stopwords=set(w.strip() for w in
                              open('stopwords.txt')):
    words = [w for w in text.split() if w not in stopwords]
    ...

Since the set is not modified, there's no harm for being mutable; IOW
it's no different than using a frozenset instead. Similarly for dicts,
lists and other mutable containers, as long as they are treated as
read-only.

George



More information about the Python-list mailing list