BESSER icon indicating copy to clipboard operation
BESSER copied to clipboard

Order of classes while iterating over set

Open FChikh opened this issue 2 years ago • 2 comments

TL;DR: Provide a topological sorting algorithm for set of classes in order to resolve references to non-defined Python classes

I faced this problem (as well as Ivan) while creating generators for Django models and Python classes. If we create an association entity within class definition, while iterating over "ends", it will cause a reference to the class, which has not been declared yet in this context. For example:

from django.db import models

class Star(models.Model):
    ...
    # reference to Movie class, causes <<"Movie" is not defined>> error
    movie = models.ManyToManyField(Movie)
    ...

# definition of Movie class
class Movie(models.Model):
    ...
    # reference to Movie class, causes <<"Studio" is not defined>> error
    studio = models.ForeignKey(Studio, on_delete=models.CASCADE)
    ...

# definition of Studio class
class Studio(models.Model):
    ...

A solution for this - add a sorting algorithm to DomainModel.get_classes() method and change return type to list, which will contain Class objects topologically sorted, e.g. in example above the order should be [Studio, Movie, Star].

FChikh avatar Nov 02 '23 15:11 FChikh

This is a well known problem that surfaces in many domains. Doublecheck whether there is not already an implementation that we could easily adapt to our specific scenario.

jcabot avatar Nov 04 '23 07:11 jcabot

Btw, I don't see how an issue can be a bug and an enhancement at the same time :-)

jcabot avatar Nov 04 '23 08:11 jcabot