tags:

views:

57

answers:

1

Currently I'm trying to write my first Python library and I've encountered the following problem:

I have the following import in my package myapp.factories:

from myapp.models import *

And the following in my package myapp.models:

from myapp.factories import *

I need the models in my factories package but inside one model I also need one of the factories. If I now call the code that needs the factory I get the following error:

NameError: global name 'MyModelFactory' is not defined

I'm pretty sure it has something to do with the order in which the scripts are loaded but I can't seem to figure out how to get these crossreferences to work.

+4  A: 

"inside one model I also need one of the factories" - just import that factory where you need it:

class SomeModel:
    def some_method(self):
        from myapp.factories import SomeFactory
        SomeFactory().do_something()
RichieHindle
Circular dependencies are the pits, in any language and many non-language contexts; this simple refactoring is one way to remove this circular dep but I would also recommend a broader and deeper reconsideration of the overall architeture -- circular deps are a "bad architecture smell" and they should be taken as hints to consider rethinking the big picture, IMHO.
Alex Martelli