Matilda
Matilda

Reputation: 1718

python circular import and accessing class

I am new to python, I was googling and reading SO for this.

I have

pin.py :

from board import Board
class pin(object):
  board_id = Int()
  my_board = store.get(Board, board_id)

  def __init__(self, val): 
    ...

board.py :

from pin import Pin
class Board(object):
   id = Int()
   def __init__(self, val): 
     ...

Board.pins = ReferenceSet(Board.id, Pin.board_id)

As you can see I need to be able to access both Pin and Board from the other class. I saw here to only do import pin and import board. But when I do that and then I do board.Board or pin.Pin for example in my pin.py I'll have my_board = store.get(board.Board, board_id) it gives me this error

AttributeError: 'module' object has no attribute 'Board'

This wasn't happening when I had the code above, but only didn't have the circular import.

To clarify my question:

How do I do a circular import and call the classes from the files being imported?

Upvotes: 1

Views: 2165

Answers (1)

BrenBarn
BrenBarn

Reputation: 251618

The real answer to your question is "don't use circular imports". Take the stuff that both modules need and put it in a third module, or combine the two modules into one.

To be more specific about what's going on in your case versus the example you linked: you can't safely use circular import references in the top-level module code of the circularly-importing-each-other modules. As the other question you linked to already explains, you must "protect" the circular references by only accessing the module contents inside functions. If you try to use each module directly from the other, as you are doing, it will never work, because neither module can finish running before it tries to use the other one, so neither module will ever get to finish running.

Upvotes: 2

Related Questions