Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #26726

Re: Unexpected behavior using contextmanager on a class method

From Peter Otten <__peter__@web.de>
Subject Re: Unexpected behavior using contextmanager on a class method
Date 2012-08-07 18:04 +0200
Organization None
References <c3319131-342a-40e9-927e-07448e8ade98@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.3060.1344355474.4697.python-list@python.org> (permalink)

Show all headers | View raw


Thomas Draper wrote:

> I want to use with..as in a "reversible circuit generator". However, it
> seems that @contextmanager changes the expected nature of the class. I
> tried to distill the problem down to a simple example.
> 
> import contextlib
> 
> class SymList:

The problem you experience has nothing to do with context managers, you have 
a mutable default argument in your __init__(). 

>     def __init__(self, L=[]):

L is initialised with an empty list exactly once, when the method is 
defined; any changes you make to the list will be seen by all instances that 
use the default. The fix is

      def __init__(self, L=None):
          if L is None:
              L = []

>         self.L = L
> 
>     @contextlib.contextmanager
>     def SymAdd(self, a):
>         self.L.append(a)
>         yield
>         self.L.append(a)
> 
> SL = SymList()
> with SL.SymAdd(3):
>     SL.L.append(5)
> print(SL.L) # Expect and see [3, 5, 3]
> SL2 = SymList() # New object. Should have default values.
> print(SL2.L) # Expect [] and see [3, 5, 3]
> 
> Why is the data member SL2.L referring to the data member SL.L? Has the
> @contextmanager somehow made all instantions of the class related?

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Unexpected behavior using contextmanager on a class method Thomas Draper <tgdrape@gmail.com> - 2012-08-07 08:30 -0700
  Re: Unexpected behavior using contextmanager on a class method Peter Otten <__peter__@web.de> - 2012-08-07 18:04 +0200
  Re: Unexpected behavior using contextmanager on a class method Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-08-07 17:45 +0000

csiph-web