Thoughts on new vs traditional idioms

Peter Otten __peter__ at web.de
Mon Mar 1 02:35:55 EST 2004


Kurt B. Kaiser wrote:

>> 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  ?

Not particular frequent, but anyway:

>>> sample = [[1,2], (3,4)]
>>> copies = [seq.__class__(seq) for seq in sample]
>>> for s, c in zip(sample, copies):
...     if s is c: print s
...
(3, 4)

Assuming all immutable classes are "smart enough":

>>> def immutable(obj, known={}):
...     try:
...             return known[obj.__class__]
...     except KeyError:
...             result = known[obj.__class__] = obj is obj.__class__(obj)
...             return result
...
>>> immutable(())
True
>>> immutable([])
False
>>>

Peter




More information about the Python-list mailing list