Need advice on python importing

George Sakkis george.sakkis at gmail.com
Fri Oct 17 19:04:42 EDT 2008


On Oct 17, 12:19 pm, Matthew Wilson <m... at tplus1.com> wrote:

> I started with a module with a bunch of classes that represent database
> tables.  A lot of these classes have methods that use other classes
> inside, sort of like this:
>
>     class C(object):
>         @classmethod
>         def c1(cls, a):
>             return a
>
>     class D(object):
>         def d1(self, a):
>             return a + C.c1(a)
>
> Notice how the d1 method on class D uses a classmethod c1 on C.  C is in
> the same module, so it's globally available.
>
> I moved my classes C and D into different files, and then I noticed that
> D now needed to import C first.  That worked fine until I wrote
> interdependent classes that couldn't import each other.
>
> So I passed in everything as parameters like this:
>
>     def d1(self, C, a):
>
> That works fine, but now I've got some methods that have six
> parameters (or more) that are entirely just for this purpose.  So, now
> instead of passing these in as parameters, I'm passing them into my
> initializer and binding them in to self.
>
> I wanted to use functools.partial to bind on these parameters like this:
>
>     d1 = functools.partial(d1, C=C)
>
> But partial objects don't get the self parameter passed in, so using
> partial is is effectively similar to decorating methods with
> staticmethod.  Here's a link to the documentation on partial that
> explains this:
>
>    http://www.python.org/doc/2.5.2/lib/partial-objects.html
>
> So, partials won't work.
>
> I suspect that there's more elegant solutions for this.
>
> All thoughts are welcome.

Cluttering the method signatures like this is worse than the problem
they're trying (unsuccessfully) to solve. You should try to resolve
the cyclic dependencies first. If it's not possible, that's probably a
sign that they should live in the same module after all.

George



More information about the Python-list mailing list