473,719 Members | 2,059 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

import error between 2 modules

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=Wor ker()
def getemployerName (self):
return self.name
def callWorker(self ,message):
self.worker.ans werCall(message )
if __name__ == "__main__":
emp=Employer()
emp.callWorker( "report to work")
workmodule.py
------------------
from empmodule import Employer
class Worker:
def __init__(self):
self.emp=Employ er()
def answerCall(self ,msg):
print "Worker :"+msg+" received
from :"+self.emp.get employerName()
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
jim
Aug 27 '08 #1
4 1699
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=Wor ker()
def getemployerName (self):
return self.name
def callWorker(self ,message):
self.worker.ans werCall(message )
if __name__ == "__main__":
emp=Employer()
emp.callWorker( "report to work")
workmodule.py
------------------
from empmodule import Employer
class Worker:
def __init__(self):
self.emp=Employ er()
def answerCall(self ,msg):
print "Worker :"+msg+" received
from :"+self.emp.get employerName()
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.Emplo yer()
#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.Work er()

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

self.emp = empmodule.Emplo yer()

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

Aug 27 '08 #2
Le Wednesday 27 August 2008 12:38:33 jimgardener, vous avez écrit*:
empmodule.py
----------
from workmodule import Worker

class Employer:
* * def __init__(self,n ):
* * * * self.name=n
* * * * self.worker=Wor ker()
* * def getemployerName (self):
* * * * return self.name
* * def callWorker(self ,message):
* * * * self.worker.ans werCall(message )
if __name__ == "__main__":
* * emp=Employer()
* * emp.callWorker( "report to work")
workmodule.py
------------------
from empmodule import Employer
class Worker:
* * def __init__(self):
* * * * self.emp=Employ er()
* * def answerCall(self ,msg):
* * * * print "Worker :"+msg+" received
from :"+self.emp.get employerName()
For this case you could do your import directly in the __init__ func and watch
the infinite loop you did in action !

empmodule.py
----------
from workmodule import Worker

class Employer:
def __init__(self,n ):
self.name=n
self.worker=Wor ker(self)
def getemployerName (self):
return self.name
def callWorker(self ,message):
self.worker.ans werCall(message )
if __name__ == "__main__":
emp=Employer()
emp.callWorker( "report to work")
workmodule.py
------------------
class Worker:
def __init__(self, employer):
from empmodule import Employer
if not isinstance(empl oyer, Employer):
raise ValueError("Not an employer")
self.emp=employ er()

--
_____________

Maric Michaud
Aug 27 '08 #3
On Aug 27, 5:37 pm, Laszlo Nagy <gand...@shopze us.comwrote:
These constructors will be calling each other forever. This will be an infinite recursion.
sorry,that was a quite stupid mistake on my part..thanks for pointing
out..
jim
Aug 27 '08 #4
jimgardener wrote:
is this kind of mutual import not allowed in python?
it is, but you need to understand how things work before you can use it
without getting yourself into trouble. this page might help:

http://effbot.org/zone/import-confusion.htm

see the "Circular Import" section for a discussion of what's going on
here, and "Which Way Should I Use" for some guidelines (pay special
attention to the last item in that list ;-)

</F>

Aug 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
6403
by: Markus Doering | last post by:
Hello, I just switched from 2.2 to Python 2.3. I am developing an XML/CGI interface to databases as a python package called "unitWrapper" containing several modules which ran fine under v2.2. Running Python2.3 under windows2000 I get import errors when a module imports another module of the same package with absolute package-names like this:
5
2476
by: Steve Holden | last post by:
This is even stranger: it makes it if I import the module a second time: import dbimp as dbimp import sys if __name__ == "__main__": dbimp.install() #k = sys.modules.keys() #k.sort() #for kk in k:
1
3068
by: mirandacascade | last post by:
O/S: Windows 2K Vsn of Python: 2.4 Currently: 1) Folder structure: \workarea\ <- ElementTree files reside here \xml\ \dom\
23
6414
by: Shane Hathaway | last post by:
Here's a heretical idea. I'd like a way to import modules at the point where I need the functionality, rather than remember to import ahead of time. This might eliminate a step in my coding process. Currently, my process is I change code and later scan my changes to make matching changes to the import statements. The scan step is error prone and time consuming. By importing inline, I'd be able to change code without the extra scan...
3
5426
by: Mudcat | last post by:
I have a directory structure that contains different modules that run depending on what the user selects. They are identical in name and structure, but what varies is the content of the functions. They will only need to be run once per execution. Example (directory level): Sys1: A B C
49
3932
by: Martin Unsal | last post by:
I'm using Python for what is becoming a sizeable project and I'm already running into problems organizing code and importing packages. I feel like the Python package system, in particular the isomorphism between filesystem and namespace, doesn't seem very well suited for big projects. However, I might not really understand the Pythonic way. I'm not sure if I have a specific question here, just a general plea for advice. 1) Namespace....
3
2005
by: kwatch | last post by:
What is the condition of module name which is available in 'from .. import ..' statement ? ---------------------------------------- import os print os.path # <module 'posixpath' from '/usr/local/ lib/python2.5/posixpath.pyc'> from posixpath import sep # (no errors) from os.path import sep # (no errors, wow!) path = os.path
10
1880
by: Thomas Guettler | last post by:
If you look at this code, you see there are two kind of ImportErrors: 1. app_name has no attribute or file managment.py: That's OK. 2. managment.py exists, but raises an ImportError: That's not OK: reraise # Import the 'management' module within each installed app, to register # dispatcher events. for app_name in settings.INSTALLED_APPS: try: __import__(app_name + '.management', {}, {}, )
0
1248
by: Murat Gunduz | last post by:
Dear list member, I am using a Linux machine (Fedora Core 7, 64 bit): Linux 2.6.21-1.3228.fc7 #1 SMP Tue Jun 12 14:56:37 EDT 2007 x86_64 I tried to compile a software (ncvtk) with the simple command below % python setup.py install ERROR: could not import Tkinter.
4
1243
by: bvdp | last post by:
Terry Reedy wrote: <snip> <snip> <snip>
0
8724
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9358
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9121
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6654
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5971
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4481
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4743
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3182
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2559
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.