0

I've done a little reading around this and it appears that I have unknowingly implemented code which is called a circular dependency. I'm looking for the easiest work around to prevent this issue.

ImportError: Cannot import name X

I have a script which essentially creates directories, these directories are then referenced in multiple other scripts as the script is designed to avoid hard coding of filepaths and so on.

CaseManager.py

import sys, os
from os.path import join

def mkdir():
    conPath = locateTool + locateCase
    if not os.path.isdir(conPath):
        try:
            os.mkdir(conPath)
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise    

    d1 = conPath + '/LiveAcquisition/'
    if not os.path.isdir(d1):
        try:
            os.mkdir(d1)
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise

    d5 = d1 + '/Filepaths/'
    if not os.path.isdir(d5):
        try:
            os.mkdir(d5)
        except OSError as esc:
            if exc.errno != errno.EEXIST:
                raise

The offending snippet of code is

ClusterInfo.py

import CaseManager

with open(d5 + '/Objects', 'a') as f:
    f.write(object_path)
f.closed

The code which is executed is:

Script1.py

import CaseManager
import ClusterInfo

def main():
    CaseManager.mkdir()
    CaseManager.main()
    ClusterInfo.main()

if __name__ == '__main__':
    main() 

Now I understand that import CaseManager is very bad practice, and that each individual variable should be called, this prevents pollution of the namespace and clashing variables. But after reading the referenced solution at the start, they advised that it was not possible to use from x import y as the value hasn't been created yet when it is being called (when I did do this, I got an error which lead me to that article in the first place)

How to I get the script to compile without the error NameError: global name 'd5' is not defined essentially

Now when I prepend d5 with CaseManager.d5 I get

AttributeError: 'module' object has no attribute 'd5'
Community
  • 1
  • 1
  • 1
    The first thing (although there's others - you don't need to check first, just try and create when using `os.mkdir` (EAFP over LBYL) and you're inconsistent between `exc` and `esc` as the exception names) is that `d5` is local to the `CaseManager.mkdir` function - so it won't be available at the module level anyway... – Jon Clements Apr 02 '16 at 13:52
  • @JonClements I did try `CaseManager.mkdir.d5` but this didn't work also, said that the function was an error rather than the module. Would it be better if I removed the module def mkdir and called it that way? – user3019191 Apr 02 '16 at 16:06
  • Well - it won't be available - as it's not a function attribute - rather it's created when the function runs... think about moving your `d`'s to the module level instead - then you can access them – Jon Clements Apr 02 '16 at 16:08

0 Answers0