Understanding of Python global variables (globals keyword)

Source: Internet
Author: User

Look at the code first:

Code One:

#!/usr/bin/python#coding:utf8x = def test ():p rint ' x= ', xtest ()

Code One execution Result:

x = 20

We have a slight modification on the basis of code one.

Code two:

x = def test ():p rint ' x= ', xx = 2 print ' Change X to ', Xtest ()

Code Two execution results:

X=traceback (most recent):  file "D:\Demo\testGlobal.py", line to <module>    test ()  file "D : \demo\testglobal.py ", line +, in test    print ' x= ', xunboundlocalerror:local variable ' x ' referenced before assignmen T>>>

Parsing the problem: we tried to reassign X to 2 in line 4th, and because of the scope of the variable, the variable x in the function body and the variable x outside the function body are not considered to be the same variable, then the third row x is not assigned so it will be executed with an error.

Let's change the code two a little bit.

Code Three:

x = def test (): Global x print ' x= ', xx = 2 print ' Change X to ', Xtest ()

Code Three execution results:

x=  20change x to  2>>>

The execution results are in line with our expectations at this point.

Results analysis, when added to the Global keyword, the x variable is set as a global variable, that is, regardless of the function body or function outside the variable can be manipulated (modified), but the problem is the security of the variable, if more than one user of the variable to operate, The value of the last variable becomes unpredictable. Therefore, it is generally not recommended to use global variables.

The usage scenario for global variables typically occurs in multiple threads, where a thread begins to operate on a global variable, which is preceded by a mutex that can be manipulated by other threads after the thread has been released. This scenario will be described in detail in subsequent blogs.



Understanding of Python global variables (globals keyword)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.