Python global variable scoping

后端 未结 1 1039
攒了一身酷
攒了一身酷 2020-12-02 00:48

Im trying to declare some global variables in some functions and importing the file with those functions into another. However, I am finding that running the function in the

1条回答
  •  再見小時候
    2020-12-02 01:18

    Globals in Python are only global to their module. There are no names that you can modify that are global to the entire process.

    You can accomplish what you want with this:

    globals.py:

    value = 0
    def default():
        global value
        value = 1
    

    main.py:

    import globals
    def main():
        globals.default()
        print globals.value
    
    if __name__ == "__main__":
        main()
    

    I have no idea whether a global like this is the best way to solve your problem, though.

    0 讨论(0)
提交回复
热议问题