dhill
dhill

Reputation: 3447

Python: How to get rid of circular dependency involving decorator?

I had got a following case of circular import (here severly simplified):

array2image.py conversion module:

import tuti

@tuti.log_exec_time # can't do that, evaluated at definition time
def convert(arr):
    '''Convert array to image.'''
    return image.fromarray(arr)

tuti.py test utils module:

import array2image

def log_exec_time(f):
    '''A small decorator not using array2image'''

def debug_image(arr):
    image = array2image.convert(arr)
    image = write('somewhere')

It failed with NameError. This didn't look right to me, as there was really no circular dependency there. I was looking for a neat way to avoid that or an explanation... and half way through writing this question I found it.

Moving the import below the decorator in tuti.py resolves NameError:

def log_exec_time(f):
    '''A small decorator not using array2image'''

import array2image

def debug_image(arr):
    image = array2image.convert(arr)
    image = write('somewhere')

Upvotes: 3

Views: 2571

Answers (1)

Unknown
Unknown

Reputation: 46821

The answer you came up with is a valid solution.

However, if you were that worried about circular dependencies, I would say that log_exec_time would belong in its own file since its not dependent on anything else in tuti.py.

Upvotes: 5

Related Questions