473,503 Members | 1,647 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

import order or cross import

Hi!

I'm having a bit of a problem with import.

I'm writing a marshalling system that based on a specification will
create one or more files containing mostly class definitions.

If there are more than one file created (and there are reasons for
creating more than one file in some instances) then they will import
each other since there may be or is interdependencies in between them.

And this is where the going gets tough.

Let's assume I have the following files:

------------- ONE.py --------------------

import TWO

class Car:
def __init__(self):
self.color = None

def set_color(self,v):
if isinstance(v,TWO.Black) or isinstance(v,TWO.White):
self.color = v

class BaseColor:
def __init__(self):
pass
def __str__(self):
return self.color

if __name__ == "__main__":
car = Car()
color = TWO.Black()
car.set_color(color)
print car.color

-------------- TWO.py -------------------

import ONE

class Black(ONE.BaseColor):
color = "Black"
def __init__(self):
ONE.BaseColor.__init__(self)

class White(ONE.BaseColor):
color = "White"
def __init__(self):
ONE.BaseColor.__init__(self)

-----------------------------------------

Now, running ONE.py causes no problem it will print "Black", but running
TWO.py I get:
AttributeError: 'module' object has no attribute 'BaseColor'

So, how can this be solved if it can be ?

To join ONE.py and TWO.py into one file could be a solution if there
where no other conditions (non-language based) that prevented it.

-- Roland

Jan 3 '07 #1
5 5312
Roland Hedberg kirjoitti:
Hi!

I'm having a bit of a problem with import.

I'm writing a marshalling system that based on a specification will
create one or more files containing mostly class definitions.

If there are more than one file created (and there are reasons for
creating more than one file in some instances) then they will import
each other since there may be or is interdependencies in between them.

And this is where the going gets tough.

Let's assume I have the following files:

------------- ONE.py --------------------

import TWO

class Car:
def __init__(self):
self.color = None

def set_color(self,v):
if isinstance(v,TWO.Black) or isinstance(v,TWO.White):
self.color = v

class BaseColor:
def __init__(self):
pass
def __str__(self):
return self.color

if __name__ == "__main__":
car = Car()
color = TWO.Black()
car.set_color(color)
print car.color

-------------- TWO.py -------------------

import ONE

class Black(ONE.BaseColor):
color = "Black"
def __init__(self):
ONE.BaseColor.__init__(self)

class White(ONE.BaseColor):
color = "White"
def __init__(self):
ONE.BaseColor.__init__(self)

-----------------------------------------

Now, running ONE.py causes no problem it will print "Black", but running
TWO.py I get:
AttributeError: 'module' object has no attribute 'BaseColor'

So, how can this be solved if it can be ?

To join ONE.py and TWO.py into one file could be a solution if there
where no other conditions (non-language based) that prevented it.

-- Roland
Maybe I'm missing something, but why is the class BaseColor in file
ONE.py and not in TWO.py?

Cheers,
Jussi
Jan 3 '07 #2
Roland Hedberg <ro************@adm.umu.sewrote:
Now, running ONE.py causes no problem it will print "Black", but running
TWO.py I get:
AttributeError: 'module' object has no attribute 'BaseColor'

So, how can this be solved if it can be ?
When you execute an import statement, it checks whether the module already
exists. If it does exist then it immediately returns the module object. If
the module does not yet exist then the module is loaded and the code it
contains is executed.

Remember that all statements in Python are executed at the time they are
encountered: there are no declarations (apart from 'global') so no looking
ahead to see what classes or functions are coming up.

One other complication in your particular instance: when you run a ONE.py
as a script the script is loaded in a module called '__main__', so 'import
ONE' will actually load a separate module which is NOT the same as the
__main__ module. Likewise when you run TWO.py as a script you have three
modules __main__ (loaded from TWO.py), ONE, and TWO.

So running TWO.py, you get:

import ONE
--- loads the module ONE and starts executing it
import TWO
--- loads the module TWO and starts executing it
import ONE
--- the module ONE already exists
(even though so far it hasn't got beyond
the import TWO line) so the empty module is returned.
class Black(ONE.BaseColor):
--- ONE doesn't have a BaseColor attribute yet so you get
an error.

The fix in this sort of case is usually to extract the base class out to a
third module. If you put BaseColor in base.py then you can safely import
that anywhere you want it.

An alternative in this case would be to edit ONE.py and move the line
'import TWO' down below the definition of BaseColor: nothing before that
actually requires TWO to have been imported yet.

However, you really should try to separate scripts from modules otherwise
the double use as both __main__ and a named module is going to come back
and bite you.
Jan 3 '07 #3
Duncan Booth wrote:
>
Remember that all statements in Python are executed at the time they are
encountered: there are no declarations (apart from 'global') so no looking
ahead to see what classes or functions are coming up.
Yes, I've seen this time and time again.
One other complication in your particular instance: when you run a ONE.py
as a script the script is loaded in a module called '__main__', so 'import
ONE' will actually load a separate module which is NOT the same as the
__main__ module. Likewise when you run TWO.py as a script you have three
modules __main__ (loaded from TWO.py), ONE, and TWO.
Hmm, that's interesting.
>
The fix in this sort of case is usually to extract the base class out to a
third module. If you put BaseColor in base.py then you can safely import
that anywhere you want it.
OK, so I'll go for this option. Takes some more intelligence in the
marshalling code but it should be doable.
An alternative in this case would be to edit ONE.py and move the line
'import TWO' down below the definition of BaseColor: nothing before that
actually requires TWO to have been imported yet.
Since no person is involved, in creating files like ONE.py and TWO.py,
this also has to be done by the marshalling code.
I've no clear idea which alternative would be best/easiest but your
first one seems clearer.
However, you really should try to separate scripts from modules otherwise
the double use as both __main__ and a named module is going to come back
and bite you.
Oh, that was only there as an example, so you could see the intent usage.

Thanks Duncan!

-- Roland
Jan 3 '07 #4
Jussi Salmela wrote:
Roland Hedberg kirjoitti:
>I'm having a bit of a problem with import.

I'm writing a marshalling system that based on a specification will
create one or more files containing mostly class definitions.
Maybe I'm missing something, but why is the class BaseColor in file
ONE.py and not in TWO.py?
This has to do with the how the specifications that the marshallings
system works with are structured. And it is therefor not something I can
control.

-- Roland
Jan 3 '07 #5
At Wednesday 3/1/2007 07:56, Duncan Booth wrote:
>However, you really should try to separate scripts from modules otherwise
the double use as both __main__ and a named module is going to come back
and bite you.
I second this. Something with a __main__ can use (import) other
modules, but shoud not be used (imported) by anyone.
--
Gabriel Genellina
Softlab SRL


__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 3 '07 #6

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

Similar topics

9
1748
by: Frantisek Fuka | last post by:
This thing keeps bugging me. It's probably some basic misunderstanding on my part but I am stumped. Let's say I have two Python files: file.py and file2.py. Their contents is as follows: ...
16
2727
by: Manlio Perillo | last post by:
Hi. I'm a new user of Python but I have noted a little problem. Python is a very good language but it is evolving, in particular its library is evolving. This can be a problem when, ad example,...
22
38502
by: Weston C | last post by:
I know of course that you can use <script src=""></script> in an HTML document to include javascript code you don't want to spill all over the page. I'm wondering if there's a way to include...
3
5804
by: Danny | last post by:
Hi again I am trying to import from an excel spreadsheet into access 2002, but the order that is in the spreadsheet is not preserved when I import. using DoCmd.TransferSpreadsheet in code. ...
0
1999
by: Kaur | last post by:
Hi, I have created a report based on a cross tab query and would like to Sort the column heading of the report based on the sort order of another field. I have three tables called survey...
7
6168
by: mandible | last post by:
Hello I'm trying to have some control on how my data is ordered depending on an input parameter my question is in a stored procedure how can I do something like this at the end of my...
2
7578
by: mmcquade | last post by:
Hey gang, I just created a crosstab query to assist in generating reports for class attendance. When I run the report (using temp hard-coded date constraints), I notice that my column...
2
1401
by: Bill Jackson | last post by:
Once again, I am having issues with imports... Until now, I thought the general guidelines were to rarely use 'from x import y' syntax, except when you really want to copy names over. However, I...
5
3485
by: bwlee | last post by:
Hi All, I'm attempting to automate the import of .txt files into Access. When I use the File > Get External Data > Import function and select my import specification, the data is imported...
0
7194
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7070
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...
0
7267
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,...
1
6976
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...
0
7449
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5566
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
3160
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...
0
3148
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
729
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.