import error between 2 modules

Laszlo Nagy gandalf at shopzeus.com
Wed Aug 27 08:37:12 EDT 2008


jimgardener wrote:
> I am new to python,and am learning from the tutorials
> i created 2 .py files like below and put the main in one of them
>
> empmodule.py
> ----------
> from workmodule import Worker
>
> class Employer:
>     def __init__(self,n):
>         self.name=n
>         self.worker=Worker()
>     def getemployerName(self):
>         return self.name
>     def callWorker(self,message):
>         self.worker.answerCall(message)
> if __name__ == "__main__":
>     emp=Employer()
>     emp.callWorker("report to work")
>
>
> workmodule.py
> ------------------
> from empmodule import Employer
> class Worker:
>     def __init__(self):
>         self.emp=Employer()
>     def answerCall(self,msg):
>         print "Worker :"+msg+" received
> from :"+self.emp.getemployerName()
>
>
> is this kind of mutual import not allowed in python?
> I am getting
> "from workmodule import Worker
> ImportError: cannot import name Worker"
>
> any advice/pointers most welcome
> thanks
>   
You are doing a circular import. Here is some things you can do:


#1. import the module names, not definitions inside them. For example:

import empmodule
....
self.emp = empmodule.Employer()


#2. place both classes in the same file




By the way, your program must semantically be wrong. When you create an 
Employer instance from your main program, it will try to create a worker 
in its constuctor:

self.worker = workmodule.Worker()

When the worker is being created, it tries to create an employer in its 
constuctor:

self.emp = empmodule.Employer()

These constructors will be calling each other forever. This will be an 
infinite recursion. In the end, no constructor call will be finished and 
you will not create any objects but reach recursion limit instead.

Best,

Laszlo




More information about the Python-list mailing list