Circular dependency in Django Rest Framework serializers

In my opinion your code is fine, because you do not have a logic circular dependency.

Your ImportError is only raised because of the way import() evaluates top level statements of the entire file when called.

However, nothing is impossible in python…

There is a way around it if you positively want your imports on top:

From David Beazleys excellent talk Modules and Packages: Live and Let Die! – PyCon 2015, 1:54:00, here is a way to deal with circular imports in python:

    from images.serializers import SimplifiedImageSerializer
except ImportError:
    import sys
    SimplifiedImageSerializer = sys.modules[__package__ + '.SimplifiedImageSerializer']

This tries to import SimplifiedImageSerializer and if ImportError is raised, because it already is imported, it will pull it from the importcache.

PS: You have to read this entire post in David Beazley’s voice.

Leave a Comment