This is a slightly fairly specific example of the common circular import problem. I (think I) know all of the common answers to the generic problem, so I was wondering what would be the best practice in the following example.
Suppose we have a module (lets call it shape.py) containing a number of related classes. For example, a Point
, Line
and Polygon
class.
Each of these classes has a class method which returns an instance of the class by populating it with data from a file.
The logical (?) layout would be to put the classes and methods for reading the data and populating the class in another module. Lets call it reader.py. This presents the problem that shape.py needs to import reader.py to access the read routines and reader.py needs to import shape.py in order to instantiate the classes.
The obvious solution is to put the contents of reader.py in shape.py. But we don't really want to do that as it is not a very clear layout and our reader.py and shape.py modules are already quite long.
The solution I have seen in many existing packages is to use local imports inside the class methods. This seems a bit clunky and fragile, and in many threads I've seen on stackoverflow it seems to be thought of as a cop-out instead of proper refactoring.
So, is there a better solution?