What is the common technique used to cross-reference in module's method?

jfong at ms4.hinet.net jfong at ms4.hinet.net
Thu Mar 17 06:48:46 EDT 2016


There are two modules (say model.py and piece.py) which has methods need to refer to each other module's methods. I saw in a book using the way below, by assigning one (the Model) object to an attribute of the other (the Piece) bject.
-------------
##model.py
import piece
...
class Model(dict):
    ...
    def all_occupied_positions(self):
        ...

    def reset_to_initial_locations(self):
        self.clear()
        for position, value in START_PIECES_POSITION.items():
            self[position] = piece.create_piece(value)
            self[position].model = self
    ...

##piece.py
...
def create_piece(value):  # Note: it's a function
   ...
   return eval(...)  # the returned object is a Piece object

class Piece():
    ...
    def moves_available(self):
        model = self.model
        ...
        if item not in model.all_occupied_positions():
            ...
    ...
-----------
Is it a common way of doing this?

Why the author use the same module name "model" for those attribute and local names? Is it a good idea or bad?

--Jach



More information about the Python-list mailing list