Method returns self?

Ignacio Vazquez-Abrams ignacio at openservices.net
Fri Oct 19 05:36:46 CEST 2001


On Thu, 18 Oct 2001, Roy Smith wrote:

> I've got a data file parser that returns a data object.  You call it
> something like this:
>
> parser = myParser()
> data = parser.parse(filename)
>
> Now, I want to give the data class a verify() method.  The parser only
> ensures that the data file has a parsable syntax, but there are also a
> number of higher-level semantic checks that we might want to do.  I have in
> mind something that you would call like this:
>
> parser = myParser()
> try:
>    data = parser.parse(filename).verify()
> except data.VerifyError:
>    print "you bozo"
>
> The idea is that verify() is a method of the data class which either
> returns self, or raises an exception.  The code would look something like:
>
> class data:
>    def verify (self):
>       if everthing is cool:
>          return self
>       else:
>          raise VerifyError
>
> My question is, will I run into garbage collection or reference count
> problems if a method returns self?  I can't quite put my finger on it, but
> I have this vague feeling I might end up with a self-referential object.

No, because in the code above the returned value of myParser.parse() only
exists for the duration of that statement. A copy of the reference returned
from ....verify(), however, is assigned to data, but trust me, it's fine.

> Now, I realize, I could just have it return None instead of self, and then
> use it like:
>
> parser = myParser()
> data = parser.parse(filename)
> try:
>    data.verify()
> except data.VerifyError:
>    print "you bozo"
>
> This would avoid the problem entirely, but it's not as interesting to think
> about :-)

Right, but you don't have to return None because that's what using return
alone or reaching the end of a function does implicitly.

Another thing you could do, if you plan to have more than one possible format,
is to have myParser.parse() do the verification of the data and return a
myData1, myData2, etc. object depending on the format.

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>

   "As far as I can tell / It doesn't matter who you are /
    If you can believe there's something worth fighting for."
       - "Parade", Garbage





More information about the Python-list mailing list