简体   繁体   中英

Python: defining a variable in callback function…not sure where

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?

If it is okay for sizeWritten to be a global (eg 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM