Thoughts on new vs traditional idioms

Kurt B. Kaiser kbk at shore.net
Mon Mar 1 00:58:48 EST 2004


python at rcn.com (Raymond Hettinger) writes:

> Copying
> -------
> To copy lists and dictionaries, the traditional idioms were l=mylist[:]
> and d=mydict.copy().
>
> When some of the builtin functions became types, a more consistent
> approach became possible, l=list(mylist) and d=dict(mydict).
>
> In general, mutable types can be copied using their type constructor.
> This will also work with the new types being introduced in Py2.4,
> s=set(myset) and d=collections.deque(mydeque).
>
> For immutable types, the type constructors are smart enough to reuse the
> existing value, so t=tuple(mytuple), s=str(mystring), and i=int(myint)
> all return the original object (same identity) which can be used as if
> it were a copy.

What do you mean, "as if it were a copy." It's just a binding to the 
original.  When would you use this notation instead of just
>>> s = myset  ?

> Taken together, the type constructors for mutable and immutable
>types encapsulate much of the knowledge in the copy module
>(pertaining to shallow copies).
>
>
> Init
> ----

[...]

> In Py2.4, the new mutable types, set() and collections.deque(), both
> offer __init__() methods with update behavior.  So, the technique is
> perfectly general and worth remembering.

>>> from collections import deque
>>> a = [1,2,3]
>>> b = deque(a)
>>> b.__init__([2,3])
>>> b
deque([1, 2, 3, 2, 3])          *deque: update
>>> c = [1,2,3]
>>> c.__init__([4,5])
>>> c
[4, 5]                          *list: replace 
>>> g = set([1, 2, 3])
>>> g.__init__([4, 5, 6])
>>> g
set([4, 5, 6])
>>> g.__init__(set([7, 8, 9]))
>>> g
set([8, 9, 7])                  *set: replace, not update
>>> g.__init__([10, 11, 12])
>>> g
set([10, 11, 12])               *set: replace, not update
>>> h = {'a':1}
>>> h.__init__(b=2)
>>> h
{'a': 1, 'b': 2}                *dict: update

general, but inconsistent.  Hard to remember IMHO.

> Idioms and Obscurity
> --------------------
> Using a=constructor(b) for copying and a.__init__(arg) for updates
> may seem obscure until they become standard idioms.  In time, I think
> they seem more general and less cryptic than the older copy and
> replace idioms, a=b[:] and a[:]=b.

These are a generalization of slicing notation.  Why learn two
notations?  __init__ is rather ugly, and doesn't always "initialize".

-- 
KBK



More information about the Python-list mailing list