acting on items passed to a method via a dictiomary

Alex Martelli aleaxit at yahoo.com
Sun Oct 17 11:13:26 EDT 2004


Diez B. Roggisch <deetsNOSPAM at web.de> wrote:

> Donnal Walter wrote:
> 
> > The following method is defined in one of my classes:
> > 
> >      def setup(self, items={}):
   ...
> First of all, don't use {} as default value for items. Many have stepped
> into this trap: While perfectly legal, it will be evaluated only once, when
> the method setup is found the first time. So then an instance of a dict is
> created. But now if subsequent calls to setup alter that dict items points
> to, they all share the same dict!! This small example illustrates that

However, there are no problems whatsoever with the issue you remark on,
as long as the method never alters the 'items' object.  As long as only
nonmutating methods get called on 'items', i.e., 'items' is practically
treated as "read-only", Donnal Walter's approach is just fine.  The
issue you remark on does deserve to be made, but it's also important to
understand when it does matter and when it doesn't.


Alex



More information about the Python-list mailing list