The del statement

George Sakkis george.sakkis at gmail.com
Thu May 8 02:26:46 EDT 2008


One of the few Python constructs that feels less elegant than
necessary to me is the del statement. For one thing, it is overloaded
to mean three different things:
(1) del x: Remove x from the current namespace
(2) del x[i]: Equivalent to x.__delitem__(i)
(3) del x.a: Equivalent to x.__delattr__('a') (or delattr(x,'a'))

(1) is useful, or even necessary, at least as long as there are only
two namespaces (local and global) instead of a separate namespace per
block, so that's ok for now. The other two though, don't justify IMO a
separate statement.

I would strongly prefer (2) to be implemented by a normal method
instead of a special syntax and method. See the inconsistency:
    s = ['a', 'b']
    s.pop(0)
    del s[0]

Likewise for dicts. Why not s.del(0) ? And just in case someone argues
"for the same reason we have __getitem__ and __setitem__", it is not
the same; the syntax for get/set (s[0], s[0] = 'a') doesn't introduce
a new keyword (or overload an existing one), it is pretty intuitive
and used across many languages. As for (3), it is pretty uncommon to
deserve its own syntax; delattr() or directly modifying self.__dict__
are good enough.

I understand that no more proposals are accepted for Python 3 but it
looks like a missed opportunity to make the language a bit simpler and
more consistent. Anyone else have an opinion on this?

George



More information about the Python-list mailing list