On Nov 20, 2:06 pm, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> Rafe <[EMAIL PROTECTED]> writes:
> > Hi,
>
> > I am in a situation where I feel I am being forced to abandon a clean
> > module structure in favor of a large single module. If anyone can save
> > my sanity here I would be forever grateful.
>
> > My problem is that classes in several modules share a common base
> > class which needs to implement a factory method to return instances of
> > these same classes.
>
> > An example to help illustrate what I mean:
> > Lets say I have the following modules with the listed classes:
> >  - baselib.py   with  BaseClass
> >  - types.py   with  TypeA, ...
> >  - special.py   with  SpecialTypeA, ...
>
> > Which would be used a bit like this:
> >>>> type_a = any_type_instance.get_type("TypeA")
> >>>> special_type = type_a.get_type("SpecialTypeA")
>
> > Again, I can get around this by dumping everything in to one module,
> > but it muddies the organization of the package a bit. This seems like
> > a problem that would come up a lot. Are there any design paradigms I
> > can apply here?
>
> It's not very clear what your problem is.  I guess your factory
> functions are defined in baselib.py whereas types.py and special.py
> import baselib, therefore you don't know how to make the factory
> function aware of the types defined in special.py and types.py.
>
> You can use cyclic import in many cases.
>
> Or (better IMHO) you can make types register themselves with the factory
> function (in which case it would have some state so it would make more
> sense to make it a factory object).
>
> --
> Arnaud

hi Arnaud,

You got my problem right, sorry it wasn't more clear.

Can you elaborate on what you mean by 'register' with the factory
function?

Also...holy [EMAIL PROTECTED], I got a clean import working! I swear I tried 
that
before with unhappy results. I'll carefully try this in my real code.

Is this the right way to impliment the imports?....

baselib.py
[1] class BaseClass(object):
[2]     def factory(self):
[3]         import typelib   # <-- import inside function
[4]         return typelib.TypeA()

typelib.py
[1] import baselib   # <-- module level import
[2]
[3] class TypeA(baselib.BaseClass):
[4]     def __init__(self):
[5]         print "TypeA : __init__()"

>>> import typelib
>>> type = typelib.TypeA()
TypeA : __init__()
>>> another_type = type.factory()
TypeA : __init__()
>>> another_type
<typelib.TypeA object at 0x00B45F10>


I am curious (not directed at Arnaud), why not have an 'include'-like
import for special cases in python (or do I not understand includes
either?)

Thanks!

- Rafe
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to