views:

198

answers:

1

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')
+3  A: 

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.

Unknown
The best solution is to move the decorator to another module and avoid circular dependency.
codeape
Yep, it's MUCH better to entirely avoid the circular dependency, than to try to skirt it with fragile solutions such as this one.
Alex Martelli
This was an obvious workaround and a reason, why I at all asked. I'm more happy with my solution, as this would be creating a module to hold 4-lines-of-code function and that's so Java :)... and it wouldn't fit the color of my license... Nah... Ausschwitz!
dhill