Global variable with imports

后端 未结 3 1283
不知归路
不知归路 2020-12-08 10:13

first.py

myGlobal = \"hello\"

def changeGlobal():
   myGlobal=\"bye\"

second.py

from first import *

changeGlobal()
pr         


        
3条回答
  •  囚心锁ツ
    2020-12-08 10:49

    Python global variables are not global

    As wassimans points out above they are essentially attributes within the scope of the module they are defined in (or the module that contains the function that defined them).

    The first confusion(bug) people run into is not realizing that functions have a local name space and that setting a variable in a function makes it a local to the function even when they intended for it to change a (global) variable of the same name in the enclosing module. (declaring the name in a 'global' statement in the function, or accessing the (global) variable before setting it.)

    The second confusion(bug) people run into is that each module (ie imported file) contains its own so called 'global' name space. I guess python things the world(globe) is the module -- perhaps we are looking for 'universal' variables that span more than one globe.

    The third confusion (that I'm starting to understand now) is where are the 'globals' in the __main__ module? Ie if you start python from the command line in interactive mode, or if you invoke python script (type the name of the foo.py from the command shell) -- there is no import of a module whose name you can use.

    The contents of 'globals()' or globals().keys() -- which gives you a list of the globals -- seems to be accessible as: dir(sys.modules['__main__']) It seems that the module for the loaded python script (or the interactive session with no loaded script), the one named in: __name__, has no global name, but is accessible as the module whose name is '__main__' in the system's list of all active modules, sys.modules

提交回复
热议问题