Python module dependency

Fire Lancer picture Fire Lancer · Oct 1, 2008 · Viewed 14.2k times · Source

Ok I have two modules, each containing a class, the problem is their classes reference each other.

Lets say for example I had a room module and a person module containing CRoom and CPerson.

The CRoom class contains infomation about the room, and a CPerson list of every one in the room.

The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room.

The problem is with the two modules importing each other I just get an import error on which ever is being imported second :(

In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg:

class CPerson;//forward declare
class CRoom
{
    std::set<CPerson*> People;
    ...

Is there anyway to do this in python, other than placing both classes in the same module or something like that?

edit: added python example showing problem using above classes

error:

Traceback (most recent call last):
File "C:\Projects\python\test\main.py", line 1, in
from room import CRoom
File "C:\Projects\python\test\room.py", line 1, in
from person import CPerson
File "C:\Projects\python\test\person.py", line 1, in
from room import CRoom
ImportError: cannot import name CRoom
room.py

from person import CPerson

class CRoom:
    def __init__(Self):
        Self.People = {}
        Self.NextId = 0

    def AddPerson(Self, FirstName, SecondName, Gender):
        Id = Self.NextId
        Self.NextId += 1#

        Person = CPerson(FirstName,SecondName,Gender,Id)
        Self.People[Id] = Person
        return Person

    def FindDoorAndLeave(Self, PersonId):
        del Self.People[PeopleId]

person.py

from room import CRoom

class CPerson:
    def __init__(Self, Room, FirstName, SecondName, Gender, Id):
        Self.Room = Room
        Self.FirstName = FirstName
        Self.SecondName = SecondName
        Self.Gender = Gender
        Self.Id = Id

    def Leave(Self):
        Self.Room.FindDoorAndLeave(Self.Id)

Answer

Constantin picture Constantin · Oct 1, 2008

No need to import CRoom

You don't use CRoom in person.py, so don't import it. Due to dynamic binding, Python doesn't need to "see all class definitions at compile time".

If you actually do use CRoom in person.py, then change from room import CRoom to import room and use module-qualified form room.CRoom. See Effbot's Circular Imports for details.

Sidenote: you probably have an error in Self.NextId += 1 line. It increments NextId of instance, not NextId of class. To increment class's counter use CRoom.NextId += 1 or Self.__class__.NextId += 1.