Note that there are some explanatory texts on larger screens.

plurals
  1. POPython copy-on-write behavior
    text
    copied!<p>I'm working on a problem where I'm instantiating many instances of an object. Most of the time the instantiated objects are identical. To reduce memory overhead, I'd like to have all the identical objects point to the same address. When I modify the object, though, I'd like a new instance to be created--essentially copy-on-write behavior. What is the best way to achieve this in Python?</p> <p>The Flyweight Pattern comes close. An example (from <a href="http://codesnipers.com/?q=python-flyweights">http://codesnipers.com/?q=python-flyweights</a>):</p> <pre><code>import weakref class Card(object): _CardPool = weakref.WeakValueDictionary() def __new__(cls, value, suit): obj = Card._CardPool.get(value + suit, None) if not obj: obj = object.__new__(cls) Card._CardPool[value + suit] = obj obj.value, obj.suit = value, suit return obj </code></pre> <p>This behaves as follows:</p> <pre><code>&gt;&gt;&gt; c1 = Card('10', 'd') &gt;&gt;&gt; c2 = Card('10', 'd') &gt;&gt;&gt; id(c1) == id(c2) True &gt;&gt;&gt; c2.suit = 's' &gt;&gt;&gt; c1.suit 's' &gt;&gt;&gt; id(c1) == id(c2) True </code></pre> <p>The desired behavior would be:</p> <pre><code>&gt;&gt;&gt; c1 = Card('10', 'd') &gt;&gt;&gt; c2 = Card('10', 'd') &gt;&gt;&gt; id(c1) == id(c2) True &gt;&gt;&gt; c2.suit = 's' &gt;&gt;&gt; c1.suit 'd' &gt;&gt;&gt; id(c1) == id(c2) False </code></pre> <p><strong>Update</strong>: I came across the Flyweight Pattern and it seemed to almost fit the bill. However, I'm open to other approaches.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload