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.
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 afterimport 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.