liveBook · Manning

Copy

As explained in Python How-To

Object copying is the technique of creating a separate object representation from an existing object.

Need to let someone edit a task, then save or cancel? Keep the original task and make a separate object for the proposed changes. Copy the instance itself—not just its `__dict__`—so the working copy remains a `Task` with its class’s methods. section 10.3 section 10.3.1

from copy import copy

task_copied = copy(task)

print(task_copied)
# output: Task('Homework', 'Math and physics')

`copy(task)` creates a `Task` instance with the same displayed data. It is a shallow copy. section 10.3.1

A shallow copy does not make separate copies of interior mutable objects. If a task has a `tags` list, `task_copied.tags.append("red")` also changes the tags visible through the original task: both instances refer to the same list. Check that relationship with `task.tags is task_copied.tags`; `is` tests object identity, while `==` tests value equality. section 10.3.2

Choose the copying behavior to match what may change:

  • Use `copy(task)` when sharing interior mutable objects is acceptable; a shallow copy can save memory. section 10.3.1 section 10.3.4
  • Use `deepcopy(task)` when edits to contained mutable objects must leave the original data intact. section 10.3.5 section 10.3.4
  • For a custom class that needs special behavior, define `__copy__` or `__deepcopy__`. For example, a custom `__copy__` could prefix the copied task’s title and create a new tags list. section 10.3.5

Object copying is distinct from copying a file. To keep a source file and place a second file at a destination path, use `shutil.copy(src, dst)`. section 11.4.4

How Python How-To covers it

How deep it goes
Works through shallow copying, demonstrates shared mutable state, contrasts deep copying, and poses custom `__copy__` behavior as a challenge.
Examples
Uses editable tasks with tags, a shared-list identity check, and files copied into subject folders.
What it assumes
Assumes familiarity with Python classes, attributes, and lists while introducing the `copy` module’s copying functions.
What you can do after
Apply it via Python’s `copy` module, choosing shallow or deep copying according to whether contained mutable objects must remain independent.
How it connects
Connects object copying to mutable lists, object identity, deep copying, special methods, and file copying.

Also explained in

Compare how 5 books explain copy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.