Python globals, locals, and UnboundLocalError

后端 未结 4 2254
长情又很酷
长情又很酷 2020-12-15 11:49

I ran across this case of UnboundLocalError recently, which seems strange:

import pprint

def main():
    if \'pprint\' in globals(): print \'pp         


        
4条回答
  •  清歌不尽
    2020-12-15 12:19

    Looks like Python sees the from pprint import pprint line and marks pprint as a name local to main() before executing any code. Since Python thinks pprint ought to be a local variable, referencing it with pprint.pprint() before "assigning" it with the from..import statement, it throws that error.

    That's as much sense as I can make of that.

    The moral, of course, is to always put those import statements at the top of the scope.

提交回复
热议问题