Python globals, locals, and UnboundLocalError

后端 未结 4 2249
长情又很酷
长情又很酷 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:40

    Where's the surprise? Any variable global to a scope that you reassign within that scope is marked local to that scope by the compiler.

    If imports would be handled differently, that would be surprising imho.

    It may make a case for not naming modules after symbols used therein, or vice versa, though.

提交回复
热议问题