Module Structure/Import Design Problem

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Nov 25 19:58:23 CET 2008


Rafe a écrit :
> On Nov 20, 2:06 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
(snip)
>>
>> 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).
>>
> 
> Can you elaborate on what you mean by 'register' with the factory
> function?

I think Arnaud means something like:

# baselib.py
class Base(object):
     _registry = {}

     @classmethod
     def register(cls, subclass):
         cls._registry[subclass.__name__] = subclass

     @classmethod
     def get_class(cls, classname):
         return cls._registry[classname]


# typelib.py
from baselib import Base

class Sub(Base):
    pass

Base.register(Sub)




> Also...holy cr at p, 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()


This is one possible way to solve circular imports, but it has some 
drawbacks - mostly, the performance hit of the import statement on each 
call to BaseClass.factory

> 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()

<ot>
This shadows the builtin type 'type'. Better to use another name here...
</ot>

> 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?)

In C,  #include <somefile.h> is a pre-processor statement that does a 
textual inclusion before compilation. Python just doesn't work that way.




More information about the Python-list mailing list