import order or cross import

R

Roland Hedberg

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
 
J

Jussi Salmela

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
 
D

Duncan Booth

Roland Hedberg said:
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.
 
R

Roland Hedberg

Duncan said:
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
 
R

Roland Hedberg

Jussi said:
Roland Hedberg kirjoitti:
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
 
G

Gabriel Genellina

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Import order question 0
Issues with writing pytest 0
TTRPG Movement 2
import bug 15
Some silly code for Easter holiday 0
A thread import problem 0
AttributeError in pygame code 4
Two Classes In Two Files 9

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
DewittMill
Top