knusperwurst
knusperwurst

Reputation: 155

Python "local variable referenced before assignment" Error despite Global key

here is my problem:

savedFileSize = 0
savedFileCount = 0
SUBFOLDER = False

def saveFile(path, filename):
    global savedFileSize
    global savedFileCount

    filepath = os.path.join(path, filename)
    if SUBFOLDER:
        try:
            subpath = os.path.join(SAVEPATH, path.split("\\", 1)[1])
            if not os.path.exists(subpath):
                os.makedirs(subpath)
            shutil.copy(filepath, subpath)
            savedFileCount += 1
            savedFileSize += os.path.getsize(filepath)/(1024*1024)
        except BaseException as e:
            logging.exception(e)
    else:
        try:
            shutil.copy(filepath, SAVEPATH)
            savedFileCount += 1
            savedFileSize += os.path.getsize(filepath)/(1024*1024)
        except BaseException as e:
            logging.exception(e)

I get the "local variable 'savedFileCount' referenced before assignment" Error the whole time. But the variable SUBFOLDER works without any Problems. Also the savedFileSize variable works without any problems.

Upvotes: 2

Views: 1500

Answers (1)

Hyperboreus
Hyperboreus

Reputation: 32429

I am glad that deleting your pyc files solved your problem. However, your code doesn't actually call for global variables. In most of the cases the (evitable) use of globals is a sign of not so good design and may cause all sorts of problems, including name clashes etc.

You could refactor easily your code without globals:

def saveFile(path, filename):
    savedFileCount, savedFileSize = 0, 0
    filepath = os.path.join(path, filename)
    if SUBFOLDER:
        try:
            subpath = os.path.join(SAVEPATH, path.split("\\", 1)[1])
            if not os.path.exists(subpath):
                os.makedirs(subpath)
            shutil.copy(filepath, subpath)
            savedFileCount = 1
            savedFileSize = os.path.getsize(filepath)/(1024*1024)
        except BaseException as e:
            logging.exception(e)
    else:
        try:
            shutil.copy(filepath, SAVEPATH)
            savedFileCount = 1
            savedFileSize += os.path.getsize(filepath)/(1024*1024)
        except BaseException as e:
            logging.exception(e)
    return savedFileCount, savedFileSize

And then in your calling scope:

totalCount, totalSize = 0
for path, filename in tobesaved:
    count, size = saveFile(path, filename)
    totalCount += count
    totalSize += size

Upvotes: 1

Related Questions