Jun 11 2011

Avoiding circular imports

Category: Pythontuxie @ 14:47

Whenever you find yourself in a situation where two modules import each other, the easiest way out is to move one of the pieces of code to an external module. Example:

secret.py

from .models import User

def get_key():
return '53cr37 k3y'

def get_user_model():
return User

models.py

from .secret import get_key
from hashlib import sha256

class User(object):
"""A user.
"""

def __init__(self, username, password):
self.username = username
self.password = sha256('%s&&%s' % (password, get_key())).hexdigest()

You may argue that this example doesn’t make much sense, and I must agree, but describes well enough the problem.

As you can see in the previous code we have 2 modules, secret.py and models.py both importing code from each other. What you should do in this case is move one of the imported bits onto a new module, for example:

secret.py

def get_key():
return '53cr37 k3y'

users.py

from .models import User

def get_user_model():
return User

Now models.py imports from secret.py and the new file users.py imports from models.py, while secret.py doesn’t import code at all. It could be described as:

users < models < secret

I disabled comments because I was sick of spam. If you want to comment on anything write me to alvaro@(this domain).