[Pulp-list] Default values in method signatures

Jay Dobies jason.dobies at redhat.com
Thu Mar 10 19:08:35 UTC 2011


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


This came up today with respect to the Filter __init__ method. The issue
surrounds the signature:  def __init__(self, id, type, description=None,
package_list=[]):

I first learned this was an issue when PyCharm started highlighting them
in our code base. From PyCharm's inspection description:

"Default argument values are evaluated only once at function definition
time, which means that modifying the default value of the argument will
affect all subsequent calls of the function. "

In other words, all Filter instances that don't pass in package_list
will point to the same list object. If they start to dork with its
contents, *all* Filter objects will reflect the package list.

A workaround could be:

def __init__(self, id, type, description=None, package_list=None):
    if not package_list:
        package_list = []
    self.package_list = package_list

That way a new list is created on each instantiation if one is not
passed in.

BTW, this is all over our code. I mentioned it back in August
(https://www.redhat.com/archives/pulp-list/2010-August/msg00030.html) so
please try to clean these up when you see them.


- -- 
Jay Dobies
RHCE# 805008743336126
Freenode: jdob
http://pulpproject.org
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.14 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJNeSGzAAoJEOMmcTqOSQHCk9EH/iqGXldsmsFhR4SNEH0MncTk
ncj4mOsq4MCL0xNJKhqX4VuBq5lXRgTvugTErleSKJYKqC5+BUV+h70jJWHvkbmg
MtQD6YY3R5O9zScYRq6IIpkLkkEfWZ9+zbxyY0iWEeyVoYSoQMVfQXWSvCn1L+kB
rxLtvWgNKG0u59EeAbb2+G5UeItD8ffNu7KnQLTTmFXYNNaV6NXTTJ2quVCfEOAm
zBE1n9UE/tuoTXaMCgFp/8XvoXPqPYzoKbLXPoqmtbCkwOGTwPQ+hn1k9XLMhofW
Js44m38QQMlBVc25e2lMY4IzuSHDa9Y4pK/n4SFqo0Lo7hmUkreg7zupvjvIAN0=
=lmpi
-----END PGP SIGNATURE-----




More information about the Pulp-list mailing list