Overthrow, Python Global Declaration

global declaration

The theme is about the scope of the glabal declaration in Python3. I wasted a few hours because the definition part was ambiguous, but I researched various things and learned, so I will keep a record.

Example of failure

This is a code that is very easy to write. It is just a sample.

sample.py


def func():
    global x
    x = 20
    print(f'func x={x}')

def main():
    x = 10
    func()
    print(f'x of main={x}')

if __name__ == '__main__':
    main()

I wonder if 20 will be output in both cases.

bash


$ python3 sample1.py 
func x=20
x of main=10

why? ?? !! !! Declare global! !! I searched for a few hours, but it was resolved. ↓↓ street.

The important thing is the scope

The declaration with global x means the following two.

--If there is an object x in the global scope, it can be treated as a ** global variable x ** in the code block (see = same identity). --If there is no object x in the global scope, declare it as a new ** global variable x ** ([This x can be handled from the global scope](https://snowtree-injune.com/2018/12/13/global- nonlocal / # toc6)))

In the previous code, x actually existed in main () (= local scope), not in the global scope. In other words, the global variable x declared in ** func () was completely different from the local variable x in main (). ** **

solution

Declare x in the global scope, not in the local scope called main ().

sample.py


def func():
    global x
    x = 20
    print(f'func x={x}')

def main():
    # x =10 This is the local scope
    func()
    print(f'x of main={x}') #You can refer to global variables (details at the bottom of this article)

if __name__ == '__main__':
    x = 10 #Define x in global scope
    main()

bash


$ python3 test.py 
func x=20
x of main=20

def main & ʻif name == ‘__ main__’: `If you simply wrote the instruction for the main () part without doing anything, this trouble would not have occurred ...

The global declaration is valid only within that code block

sample.py


def func():
    #global x If you do not declare global here
    x = 20
    print(f'func x={x}')

def main():
    global x
    func()
    print(f'x of main={x}')

if __name__ == '__main__':
    x = 10 #Define x in global scope
    main()

bash


$ python3 sample1.py
func x=20
x of main=10

Since I made a global declaration in main (), I wondered if I needed a global declaration in func () called from there, but that wasn't the case.

See the dogma Official Documentation for reasons. It's pretty easy to understand if you read it again.

The global statement is a declarative statement that is maintained throughout the current block of code. The global statement means to specify that the listed identifiers should be interpreted as global variables. It is not possible to assign to a global variable without using global, but you can use a free variable to refer to a global variable without declaring it global.

Does the fact that the declaration is maintained in ** "the entire current code block" **, conversely, has no effect outside the code block? At the moment when x = 20 is assigned (defined) in func (), it is considered that the local variable x is defined instead of the global variable being rewritten.

solution

sample.py


def func():
    global x #func()Global Declaration
    x = 20
    print(f'func x={x}')

def main():
    global x
    func()
    print(f'x of main={x}') 

if __name__ == '__main__':
    x = 10 #Define x in global scope
    main()

bash


$ python3 test.py 
func x=20
x of main=20

If you declare global in both main () and func (), you can treat x in the global scope as a global variable x in the same way.

It can be referenced without a global declaration.

for your information. You can refer to any object in global scope without declaring global. Of course, it cannot be rewritten. Defined as a local variable the moment you assign a value.

sample.py


def func():
    x = 20
    print(f'func x={x}')

def main():
    func()
    print(f'x of main={x}') 

if __name__ == '__main__':
    x = 10 #Define x in global scope
    main()

bash


$ python3 test.py 
func x=20
x of main=10

Neither is declared global. Main () can refer to x in global scope because it can only refer to global variables. In func (), the local variable x is defined the moment x = 20 is executed, and it will be treated as a completely different thing from the global variable x in the global scope.

Summary

If you do something you are not used to, you will get stuck in various places. Let's do it because you will deepen your learning (I want to believe) while reading the document for the solution.

Below, articles that were easy to understand while studying this time (although links are also provided in the text)

-I tried to examine the questions related to the declaration of global and nonlocal | Snow Tree in June - Python global declaration [Reason why declaration is required when rewriting] </ title></a> -<a href="https://qiita.com/amedama/items/5970ae0f317796c5e723"><title> nonlocal subject --Qiita </ title></a> ← This is not directly related to this article, but I will introduce it because it was easy to understand.</p> <!-- ENDDDDDDDDDDDDDDDDDDDDDDDDDDDDD --> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- post_new_ui_horiz --> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5469278205356604" data-ad-slot="4209814965" data-ad-format="auto" data-full-width-responsive="true"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> <div style="margin-top: 30px;"> <div class="link-top" style="margin-top: 1px;"></div> <p> <font size="4">Recommended Posts</font> <!-- BEGIN LINK ************************* --> <div style="margin-top: 10px;"> <a href="/en/08c4979748a8654e4dc5">Overthrow, Python Global Declaration</a> </div> <div style="margin-top: 10px;"> <a href="/en/3a1212e785fc53114b5b">Record global IP with python</a> </div> <div style="margin-top: 10px;"> <a href="/en/c16aaff0adf63acca8c7">Declaration of C global variables</a> </div> <div style="margin-top: 10px;"> <a href="/en/0acf2cd1326d1e27b80b">Initializing global variables using Python decorators</a> </div> <div style="margin-top: 10px;"> <a href="/en/2c2d615040a9adaa6d33">Python</a> </div> <div style="margin-top: 10px;"> <a href="/en/88254b69b1510c3d7fbf">Using global variables in python functions</a> </div> <div style="margin-top: 10px;"> <a href="/en/0cb2a73f2a5e3ee34249">[Python3] Dynamically define global variables in functions</a> </div> <div style="margin-top: 10px;"> <a href="/en/6df1419767e8acb99dd7">Difference between nonlocal and global in Python</a> </div> <div style="margin-top: 10px;"> <a href="/en/941be72605c8cccd2e08">The story of manipulating python global variables</a> </div> <div style="margin-top: 10px;"> <a href="/en/bfe0c39b812de5b3dbf7">[Introduction to Udemy Python3 + Application] 8. Variable declaration</a> </div> <!-- END LINK ************************* --> </p> </div> </div> </div> <div class="footer text-center" style="margin-top: 40px;"> <!-- <p> Licensed under cc by-sa 3.0 with attribution required. </p> --> </div> <script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@10.1.2/build/highlight.min.js"></script> <script> $(document).ready(function() { var cfg_post_height = 60; var cfg_per = 0.51; var ads_obj = $('<ins class="adsbygoogle" style="display:block; text-align:center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-5469278205356604" data-ad-slot="7950405964"></ins>'); $('pre code').each(function(i, e) {hljs.highlightBlock(e)}); function getDocumentOffsetPosition( el ) { var _x = 0; var _y = 0; while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) { _x += el.offsetLeft - el.scrollLeft; _y += el.offsetTop - el.scrollTop; el = el.offsetParent; } return { top: _y, left: _x }; } if ( $( "#article202011" ).length ) { var h1_pos = getDocumentOffsetPosition($('h1')[0]); var footer_pos = getDocumentOffsetPosition($('.link-top')[0]); var post_distance = footer_pos.top - h1_pos.top; // console.log('h1_pos: '+ h1_pos.top); // console.log(cfg_post_height) if((post_distance/h1_pos.top)>=cfg_post_height) { // console.log('tesssssssssssssssssssssssssssssssss'); $( ".container p" ).each(function( index ) { var p_tag_pos = $(this).position().top; var dis = p_tag_pos - h1_pos.top; var per = dis/post_distance; if(per>cfg_per) { ads_obj.insertAfter($(this)); (adsbygoogle = window.adsbygoogle || []).push({}); console.log( index + ": " + $( this ).text() ); return false; } }); } } }); </script> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> <!-- ads --> <script data-ad-client="ca-pub-5469278205356604" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" type="d7540fe192d881abe59fcf57-text/javascript"></script> <!-- end ads --> </body> </html><script src="/cdn-cgi/scripts/7d0fa10a/cloudflare-static/rocket-loader.min.js" data-cf-settings="9ab40fc315cd80e6cedceb3e-|49" defer></script>