Use of “global” keyword in Python

后端 未结 10 2452
既然无缘
既然无缘 2020-11-21 05:05

What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to us

相关标签:
10条回答
  • 2020-11-21 05:30

    While you can access global variables without the global keyword, if you want to modify them you have to use the global keyword. For example:

    foo = 1
    def test():
        foo = 2 # new local foo
    
    def blub():
        global foo
        foo = 3 # changes the value of the global foo
    

    In your case, you're just accessing the list sub.

    0 讨论(0)
  • 2020-11-21 05:32

    This is explained well in the Python FAQ

    What are the rules for local and global variables in Python?

    In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

    Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

    https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

    0 讨论(0)
  • 2020-11-21 05:33

    This is the difference between accessing the name and binding it within a scope.

    If you're just looking up a variable to read its value, you've got access to global as well as local scope.

    However if you assign to a variable who's name isn't in local scope, you are binding that name into this scope (and if that name also exists as a global, you'll hide that).

    If you want to be able to assign to the global name, you need to tell the parser to use the global name rather than bind a new local name - which is what the 'global' keyword does.

    Binding anywhere within a block causes the name everywhere in that block to become bound, which can cause some rather odd looking consequences (e.g. UnboundLocalError suddenly appearing in previously working code).

    >>> a = 1
    >>> def p():
        print(a) # accessing global scope, no binding going on
    >>> def q():
        a = 3 # binding a name in local scope - hiding global
        print(a)
    >>> def r():
        print(a) # fail - a is bound to local scope, but not assigned yet
        a = 4
    >>> p()
    1
    >>> q()
    3
    >>> r()
    Traceback (most recent call last):
      File "<pyshell#35>", line 1, in <module>
        r()
      File "<pyshell#32>", line 2, in r
        print(a) # fail - a is bound to local scope, but not assigned yet
    UnboundLocalError: local variable 'a' referenced before assignment
    >>> 
    
    0 讨论(0)
  • 2020-11-21 05:33

    Any variable declared outside of a function is assumed to be global, it's only when declaring them from inside of functions (except constructors) that you must specify that the variable be global.

    0 讨论(0)
  • 2020-11-21 05:37

    Global makes the variable "Global"

    def out():
        global x
        x = 1
        print(x)
        return
    
    
    out()
    
    print (x)
    

    This makes 'x' act like a normal variable outside the function. If you took the global out then it would give an error since it cannot print a variable inside a function.

    def out():
         # Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
        x = 1
        print(x)
        return
    
    
    out()
    
    print (x)
    
    0 讨论(0)
  • 2020-11-21 05:42

    Accessing a name and assigning a name are different. In your case, you are just accessing a name.

    If you assign to a variable within a function, that variable is assumed to be local unless you declare it global. In the absence of that, it is assumed to be global.

    >>> x = 1         # global 
    >>> def foo():
            print x       # accessing it, it is global
    
    >>> foo()
    1
    >>> def foo():   
            x = 2        # local x
            print x 
    
    >>> x            # global x
    1
    >>> foo()        # prints local x
    2
    
    0 讨论(0)
提交回复
热议问题