Reference imported class from within imported class
<p>For a chess board, imagine there's a <code>Board</code> class, with a <code>squares</code> attribute, which is an array of <code>Square</code> instances. The file structure is that there is <code>main.py</code>, <code>board.py</code>, <code>square.py</code>, and an empty <code>__init__.py</code> (I have to say I don't fully understand the purpose of the latter... but apparently that's the way to do things). These are all in the same directory. (I've not done anything in Python involving multiple files before.)</p>

<p>In <code>main.py</code> I want to instantiate a <code>Board</code> object. Here's the contents of <code>main.py</code>:</p>

<pre><code>from board import Board
from square import Square

board = Board()
</code></pre>

<p>here's <code>square.py</code>:</p>

<pre><code>class Square:
    def __init__(self):
        pass
        #this class doesn't do anything yet
</code></pre>

<p>and here's <code>board.py</code>:</p>

<pre><code>class Board:
    row_count = 8
    column_count = 8

    def __init__(self):
        self.squares = self.generate_squares()

    def generate_squares(self):
        squares = {}
        for i in range(0, self.row_count * self.column_count):
            squares[i] = Square()
        return squares
</code></pre>

<p>However, when I run <code>main.py</code> I get told that there's an error on the <code>squares[i] = Square()</code> line; namely that <code>NameError: global name 'Square' is not defined</code>.</p>

<p>I've tried changing it to <code>squares[i] = square.Square()</code> but that yields the same error.</p>

<p>If I remove the <code>import</code> statements and just copy the class definitions into <code>main.py</code> then the instantiation works fine, so that pinpoints the issue down to being related to the <code>import</code> statements themselves.</p>

<p>In main.py you import both classes, however, Board has no way to see Square, and vice versa. Add "import Square" to your Board class, and remove it from main.py.</p>

python class namespaces python-import