[Answered ]-How to avoid code duplication with similar Django model methods?

2👍

Use a string and call getattr on the object to get the callable function.

def list_withindirect(self, fn1):
    direct = getattr(self, fn1)()
    withindirect = set(direct)
    for d in direct:
         withindirect |= set(d.list_withindirect(fn1))

    return list(withindirect)

def list_ancestors(self):
     return self.list_withindirect('list_parents')
👤2ps

0👍

This looks like the issue in bound and unbound methods problem.

When you’re initially pass self.list_parents to self.list_withindirect(list_direct) everything is OK.

But when you’re recursively pass the same! self.list_parents to d.list_withindirect (i.e. to descendants), you’re accidentally populate your direct variable with parents of the topmost caller object, instead of d.

For example, it may be resolved using getattr, like it was answered by 2ps (upd: the error in his original code was found in comments there).

Leave a comment