Need advice on python importing
Matthew Wilson
matt at tplus1.com
Fri Oct 17 18:20:57 EDT 2008
On Fri 17 Oct 2008 04:52:47 PM EDT, Steve Holden wrote:
> Matthew Wilson 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.
>
> Explain why you are using classmethods instead of regular methods in the
> first case (I appreciate your actual code will be rather more complex
> than your examples).
Hi Steve, I'm using SQLObject classes, and joining one table with
another requires either the class or an instance for the class. So, I
could pass in instances of all the classes, and I'd be at the same
point. I just don't like seeing functions with lots and lots of
parameters.
Thanks for the feedback!
More information about the Python-list
mailing list