python - Local variable referenced before assignement -


this question has answer here:

i going crazy. simple callback function doesn't recognize variable assigned right before in it's parent scope. local variable 'elapsed' referenced before assignment error`. why?

total = os.path.getsize(filename) elapsed = 0  def progress_print(chunk):     elapsed += len(chunk)  # elapsed apparently unassigned??     percent = float(elapsed) / float(total) * 100     print '  copied %s%%\033[a' % int(percent)  ftp.upload(filename, temp_path, callback=progress_print) 

you're trying assign global. python makes explicitly that.

def progress_print(chunk):     global elapsed     elapsed += len(chunk) 

in general pretty sign need refactor code until don't need globals more.

note assignment , access different beasts - former requires explicitly declare globals, latter not. case in point, total variable global not attempt assign it, hence python not complain.

the programming faq goes more detail:

what rules local , global variables in python?

in python, variables referenced inside function implicitly global. if variable assigned new value anywhere within function’s body, it’s assumed local. if variable ever assigned new value inside function, variable implicitly local, , need explicitly declare ‘global’.

though bit surprising @ first, moment’s consideration explains this. on 1 hand, requiring global assigned variables provides bar against unintended side-effects. on other hand, if global required global references, you’d using global time. you’d have declare global every reference built-in function or component of imported module. clutter defeat usefulness of global declaration identifying side-effects.


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -