Dennis Lee Bieber wrote: > On Sat, 15 Nov 2008 01:40:04 -0800 (PST), Rick Giuly > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: > >> Why is python designed so that b and c (according to code below) >> actually share the same list object? It seems more natural to me that >> each object would be created with a new list object in the points >> variable. >> > This is a FAQ... default arguments are evaluation only ONCE, during > the "compilation" of the function. > >> class Blob: >> def __init__(self, points=[]): >> self._points = points >> > The preferred/recommended form is to use (very explicit, one test, > one "assignment") > > def __init__(self, points=None): > if points: > self._points = points > else: > self._points = [] > > or (shorter; one test, potentially two "assignments") > > def __init__(self, points=None): > if not points: points = [] > self._points = points > I hesitate to beat the thoroughly obvious to death with a stick, but this is a *very* bad way to make the test. If you are using None as a sentinel to indicate that no argument was provided to the call then the correct test is
if points is None: points = [] The code shown fails to distinguish between passing an empty list and not passing an argument at all. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list