0

Excerpt:

file = open("D:\\DownloadFolder\\test.mp3", "wb")

def callback(data):
    file.write(data)
    sizeWritten += len(data)
    print(sizeWritten)

connect.retrbinary('RETR test.mp3', callback)
print("completed")

Python obviously complains that I didn't define sizeWritten, but I'm not sure where I should define it. If I put sizeWritten = 0 before the function it still gives an error local variable 'sizeWritten referenced before assignment. How should I do this?

wasmachien
  • 969
  • 1
  • 11
  • 28

1 Answers1

1

If it is okay for sizeWritten to be a global (e.g. there is only ever going to be one callback active at a time), you can mark it as such in your function:

file = open("D:\\DownloadFolder\\test.mp3", "wb")
sizeWritten = 0

def callback(data):
    global sizeWritten
    file.write(data)
    sizeWritten += len(data)
    print(sizeWritten)

and any assignments to the name in callback alter the global.

In Python 3, you can also use a closure, and the nonlocal keyword:

def download(remote, local):
    file = open(local, "wb")
    sizeWritten = 0

    def callback(data):
        nonlocal sizeWritten
        file.write(data)
        sizeWritten += len(data)
        print(sizeWritten)

    connect.retrbinary('RETR ' + remote, callback)
    print("completed")

This encapsulates the sizeWritten and file objects in a local namespace, at least.

However, you could get the same information directly from the open file file object:

def callback(data):
    file.write(data)
    print(file.tell())
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343