callbacks within classes

Adrian Graham aag at stanford.edu
Mon Apr 2 18:22:57 EDT 2001


I'm in the process of writing a class based on a module that I have
previously written. The problem that I'm running across is that since "self"
is always the first argument to any function within a class, functions that
I have been using as callbacks no longer work since their signature has
changed to include self.

For instance, what I used to code as this:

def InsertDirectories():
    os.path.walk(path, InsertDirectory, rs)

def InsertDirectory(rs, dirname, names):
    ...

I'd like to code as this:

class FileManager:

    def __init__(self):
        self.path = << some path >>
        self.rs = << a record set >>

    def InsertDirectories(self):
        os.path.walk(self.path, self.InsertDirectory, self.rs)

    def InsertDirectory(rs, dirname, names):
        ...

Unfortunately, I can't code it this way, since InsertDirectory's signature
is now: InsertDirectory(self, rs, dirname, names), which doesn't match
os.path.walk's callback signature. I know the easy (and inelegant) way to
fix this problem is to simply move InsertDirectory outside of the class.
This doesn't really make sense to me since the functionality really should
be contained within the class.

I have the feeling that there is some elegant way to do what I want with
Python, but that my C++/Java experience is getting in the way. Any
suggestions?

Thanks,

Adrian





More information about the Python-list mailing list