confused by bindings
Sam Falkner
samf+usenet at frii.com
Wed Sep 19 15:50:02 EDT 2001
Mitchell Morris <mitchell.morris at cingular.com> writes:
> Sam Falkner <samf+usenet at frii.com> wrote in
> news:ii7k7yvqi87.fsf at central.sun.com:
>
> > I'm confused. I'm a relative newbie, but am still surprised that I
> > can't make this work.
> >
> > What I want to do is to have my test module set "stuff" in one of the
> > other modules, do its tests, and then check the results. Code might
> > be more clear:
> >
> > --- file data.py ---
> >
> > class Cell:
> > count = 0
> > def __init__(self, stuff):
> > self.count += 1
> > self.stuff = stuff
> > print 'count is', self.count
> Well, I learn something new every day. I would have expected this to
> raise a NameError on the "self.count += 1" line. It doesn't though
> ... I'll have to revisit my understanding of scoping now.
I might have thought this too, but look at the wonderful Borg recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
Aren't they doing exactly what I was doing?
self.__dict__ = self.__shared_state
As I mentioned before, I tried using the "borg pattern" for my test
suite, and it didn't work either. If anyone is curious, I can
re-create the failure.
> The short answer is that "self.count" isn't bound to the same thing as
> "Cell.count". "self.count" is an attribute of the instance: each new Cell
> instance gets its own copy. If you want to manipulate the class attribute,
> then you have to say so via "Cell.count += 1" instead.
I've tried it this way before. I just (re)tried this, and the test
passes, if I run only that test case. But, if I run all my test
cases, it fails again with 5677 != 0; in other words, data.Cell.count
is 0 when looked at from my test module.
re-inserting my test case:
--- file test.py ---
class CellTestCase(unittest.TestCase):
def testforleaks(self):
data.Cell.count = 0
# do a whole bunch of stuff
# x = a gnarly collection of Cell objects
# count number of Cell objects in x
self.failUnlessEqual(count-of-Cells-from-x, data.Cell.count)
You can see that I reset the counter, via data.Cell.count = 0, to
clean up from the other test cases. As I mentioned above, my test now
succeeds when I try it your way, but not if I run the whole test suite.
> > Okay, I feel stupid here. What am I doing wrong?
> My guess is you're still wearing your Java hat, but I'm not entirely sure.
I'm offended, but only slightly. ;-)
Help! I'm running Python 2.1.1; I don't yet suspect a Python bug, but
I'm getting more confused by the minute.
- sam
More information about the Python-list
mailing list