Is this unpythonic?

Frank Millman frank at chagford.com
Sun May 10 04:58:44 EDT 2015


"Johannes Bauer" <dfnsonfsduifb at gmx.de> wrote in message 
news:min3f0$2gh$1 at news.albasani.net...
On 08.05.2015 14:04, Dave Angel wrote:

> > It might be appropriate to define the list at top-level, as
> >
> > EMPTY_LIST=[]
> >
> > and in your default argument as
> >     def x(y, z=EMPTY_LIST):
> >
> > and with the all-caps, you're thereby promising that nobody will modify
> > that list.

> I think it's a really bad idea to use a module-global mutable
> "EMPTY_LIST". It's much too easy this happens:

> # Globally
> >>> EMPTY_LIST = [ ]

> # At somewhere in the code at some point in time
> >>> foo = EMPTY_LIST
> >>> foo.append(123)
> >>> print(foo)
> [123]

> # Some other place in code
> >>> bar = EMPTY_LIST
> >>> print(bar)
> [123]


A fair point. How about this as an alternative?

If one were to use this technique at all, it would be necessary to add a 
comment at the top explaining the reason for this odd declaration.

It is then a simple extra step to say -

EMPTY_L:IST = ()

and if required -

EMPTY_DICT = ()

and expand the explanation to show why a tuple is used instead.

So if there was a situation where the overhead of testing for None became a 
problem, this solution offers the following -

1. it solves the 'overhead' problem
2. it reads reasonably intuitively in the body of the program
3. it is safe
4. it should not be difficult to write a suitable self-explanatory comment

Frank






More information about the Python-list mailing list