[Python-Dev] Decimal - context manipulation

Tim Peters tim.one at comcast.net
Wed Apr 21 12:13:16 EDT 2004

[Batista, Facundo]
> ...
> Regarding a copy() method in Context class, don't know. It's really
> easy to implement, but don't know if the standard preference is to
> get a copy method inside each data type (I'm confused about
> dictionaries having a copy method and lists, for example, not having
> it).

There have always been several succinct ways to get a (shallow) copy of a
list, like

    copied_list = list(original)


    copied_list = original[:]

For dicts, while you can do

    copied_dict = dict(original)

today, at the time dict.copy() was introduced you could not do that.

I usually add a .copy() method to my mutable types, like so:

class MyClass:
    def __copy__(self):
        return build_a_shallow_copy_of(self)
    copy = __copy__

Note that __copy__ is a special name, and the standard copy.copy(thing)
automatically invokes thing.__copy__() if thing has a __copy__() method.
The "copy = __copy__" line then supplies that method directly to class users
too under a conventional name.  So, after the above, copy.copy(thing) and
thing.copy() both work.

More information about the Python-Dev mailing list