views:

39

answers:

2

I have a project that is organized something like

project/
    __init__.py
    builder.py
    component/
        __init__.py

Within builder.py, I have a class called Builder that has several class attributes in order to implement the Borg pattern. The trouble arises when I try to import Builder in component/__init__.py and make changes to class attributes. It seems that whatever changes I make to the class attributes in the package are undone when the function returns.

UPDATE: Here is a simple example of what is happening.

builder.py

class Builder(object):
    attribute = True

import component

print Builder.attribute

component/__init__.py

from project.builder import Builder

Builder.attribute = False

Output:

False
True

Judging by the fact that two lines are printed, I would guess that the code in builder.py is being executed twice, which resets the value of attribute to True.

A: 

You should really show (a simplified version of) your code. Something like (assuming e.g. that project is in sys.path):

import builder
builder.Builder.baah = 'boo!'

in component/__init__.py, for example, should work just fine with no "undoing" nor "resetting".

But what code exactly are you using instead, to perform those "whatever changes"...?

Alex Martelli
+1  A: 

What you have is a circular import: builder imports component, component imports builder.

At the time builder imports component, builder is not yet fully constructed. Then component imports builder, which executes the rest of builder module (all after import component). Later, when component is loaded, builder continues again with everything after import component.

Note that the behaviour would be different if component was loaded first!

Basically, you should not do circular imports. Try to organise the code in some other way.

zvonimir
I suppose I'll have to bite the bullet and restructure things...
Colorado