Skip to content

Instantly share code, notes, and snippets.

@mearns
Created April 16, 2018 15:25
A trivial example of a circular dependency in python

If you run python a.py from this directory, you get an error such as:

Traceback (most recent call last):
  File "a.py", line 1, in <module>
    import b
  File "./b.py", line 1, in <module>
    import a
  File "./a.py", line 3, in <module>
    b.bar()
AttributeError: 'module' object has no attribute 'bar'

I believe it runs something like this:

  1. Python loads module a and begins executing it: module a now exists as an object but is not yet fully defined.
  2. The first statement in a is import b, so the runtime loads module b and begins executing it. module b now exists as an object but it is likewise not yet fully defined.
  3. The first statement in b is import a, so the runtime looks for module a.
  4. Runtime finds that module a has already been created and is in the middle of being executed, so it resumes executing a where it left off.
  5. Where a left off, is was expecting to get back the object of module b.
  6. The runtime identifies that module b already exists as an object, so makes it available to a. However, it is not yet fully defined.
  7. Thus, when module a attempts to execute the next line, b.bar(), there is no bar attribute on the b module object, and you get the above error.

Note that if you remove the import a from module b, it works fine.

import b
b.bar()
import a
def bar():
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment