dubeegee
dubeegee

Reputation: 781

python importing modules error for dependencies

I'm trying to understand the whole Python importing / modules / package business, but I'm stuck on this particular issue.

My directory structure:

.
├── README.md
├── mypackage
│   ├── __init__.py
│   ├── red.py
│   ├── blue.py
│   ├── green.py
│   └── tests
│       └── red_tests.py
│       └── green_tests.py
└── go.py

and my importing code looks like this:

# __init__.py
from red import Red 
from green import Green 

# blue.py
from red import Red

# green.py
from red import Red
from blue import Blue

# go.py
from mypackage import Red, Green

but running go.py gives this error when trying to access a static class variable of the Green class:

NameError: global name 'Green' is not defined

How can I fix this?


EDIT

Apologies - it turned out to be a circular dependency problem. I apologize for the confusion!

Upvotes: 1

Views: 939

Answers (2)

Morgan Wilde
Morgan Wilde

Reputation: 17295

Python imports modules with relation to your current PATH, you can find out what it is this way:

import os
print os.environ['PYTHONPATH'].split(os.pathsep)

Now when importing stuff in any of your .py files, write the import location with the relation to your PATH.

So if say your PATH was project/ (where the "project" directory is the root directory of your provided file structure), then green.py would be accessible using this syntax:

import mypackage.green

Upvotes: 1

Paul Yin
Paul Yin

Reputation: 1759

try create a file __init__.py in the same directory with go.py

Upvotes: 1

Related Questions