Using global variables between files?

前端 未结 7 1462
轻奢々
轻奢々 2020-11-22 03:43

I\'m bit confused about how the global variables work. I have a large project, with around 50 files, and I need to define global variables for all those files.

What

相关标签:
7条回答
  • 2020-11-22 04:12

    Using from your_file import * should fix your problems. It defines everything so that it is globally available (with the exception of local variables in the imports of course).

    for example:

    ##test.py:
    
    from pytest import *
    
    print hello_world
    

    and:

    ##pytest.py
    
    hello_world="hello world!"
    
    0 讨论(0)
  • 2020-11-22 04:13

    See Python's document on sharing global variables across modules:

    The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).

    config.py:

    x = 0   # Default value of the 'x' configuration setting
    

    Import the config module in all modules of your application; the module then becomes available as a global name.

    main.py:

    import config
    print (config.x)
    

    or

    from config import x
    print (x)
    

    In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

    0 讨论(0)
  • 2020-11-22 04:13

    You can think of Python global variables as "module" variables - and as such they are much more useful than the traditional "global variables" from C.

    A global variable is actually defined in a module's __dict__ and can be accessed from outside that module as a module attribute.

    So, in your example:

    # ../myproject/main.py
    
    # Define global myList
    # global myList  - there is no "global" declaration at module level. Just inside
    # function and methods
    myList = []
    
    # Imports
    import subfile
    
    # Do something
    subfile.stuff()
    print(myList[0])
    

    And:

    # ../myproject/subfile.py
    
    # Save "hey" into myList
    def stuff():
         # You have to make the module main available for the 
         # code here.
         # Placing the import inside the function body will
         # usually avoid import cycles - 
         # unless you happen to call this function from 
         # either main or subfile's body (i.e. not from inside a function or method)
         import main
         main.mylist.append("hey")
    
    0 讨论(0)
  • 2020-11-22 04:14

    Your 2nd attempt will work perfectly, and is actually a really good way to handle variable names that you want to have available globally. But you have a name error in the last line. Here is how it should be:

    # ../myproject/main.py
    
    # Import globfile    
    import globfile
    
    # Save myList into globfile
    globfile.myList = []
    
    # Import subfile
    import subfile
    
    # Do something
    subfile.stuff()
    print(globfile.myList[0])
    

    See the last line? myList is an attr of globfile, not subfile. This will work as you want.

    Mike

    0 讨论(0)
  • 2020-11-22 04:18

    The problem is you defined myList from main.py, but subfile.py needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file settings.py. This file is responsible for defining globals and initializing them:

    # settings.py
    
    def init():
        global myList
        myList = []
    

    Next, your subfile can import globals:

    # subfile.py
    
    import settings
    
    def stuff():
        settings.myList.append('hey')
    

    Note that subfile does not call init()— that task belongs to main.py:

    # main.py
    
    import settings
    import subfile
    
    settings.init()          # Call only once
    subfile.stuff()         # Do stuff with global var
    print settings.myList[0] # Check the result
    

    This way, you achieve your objective while avoid initializing global variables more than once.

    0 讨论(0)
  • 2020-11-22 04:18

    Hai Vu answer works great, just one comment:

    In case you are using the global in other module and you want to set the global dynamically, pay attention to import the other modules after you set the global variables, for example:

    # settings.py
    def init(arg):
        global myList
        myList = []
        mylist.append(arg)
    
    
    # subfile.py
    import settings
    
    def print():
        settings.myList[0]
    
    
    # main.py
    import settings
    settings.init("1st")     # global init before used in other imported modules
                             # Or else they will be undefined
    
    import subfile    
    subfile.print()          # global usage
    
    0 讨论(0)
提交回复
热议问题