Home python Using global in Python

Using global in Python

Author

Date

Category

Hello, I’m getting acquainted with python and after C++ I absolutely don’t understand the principle of using global variables. If you specify global for the variable in def, then whether its value can be used outside of this function, I definitely cannot. Maybe just because I’m a beginner and the obvious things are still too complicated for me.

def check ():
  global urokb_in
  urokb_in = 1
  with open ('users.txt', 'r') as f:
    line = f.readline ()
    f.close ()
  with open ('progress.txt', 'r') as k:
    while True:
      global uroka_in
      lines = k.readline ()
      if line == lines.rstrip ():
        uroka_in = int (k.readline (). rstrip ())
        urokb_in = uroka_in + 1
        uroka_str = str (uroka_in)
        urokb_str = str (urokb_in)
        lines.replace (uroka_str, urokb_str)
        k.close ()
        break
      if not lines:
        k.close ()
        urokb_in = 1
        with open ('progress.txt', 'a') as j:
          j.write (line)
          j.write ('\ n')
          j.write (str (urokb_in))
          j.write ('\ n')
          j.close ()
          break
  if urokb_in == 1:
    educate__scr = PhotoImage (file = 'e_scr_1.png')
    educate_label = Label (root, image = educate__scr)
    educate_label.place (x = 0, y = 0)

More experienced coders, tell me how to fix it.
SyntaxError: name ‘urokb_in’ is used prior to global declaration


Answer 1, authority 100%

If you do not specify global or nonlocal, then x = inside the function creates a local variable .

If you want to create a new global variable / or override the old one inside a function (not at the global level), then you can use global. This can be useful when working with a multiprocessing module to inherit the desired globals from the parent process:

def init (shared_arr_):
  global shared_arr
  shared_arr = shared_arr_ # must be inherited, not passed as an argument

Complete code example .

If you just want to use an existing global variable without overriding it, then global is not needed (otherwise, for example, you would have to declare global in every function, every used module, every global function).

I’m a beginner and the obvious things are still too complicated for me

For beginners: don’t override global variables at all , that is, avoid global . Consider every occurrence of global in your code as an error unless there is a specific reason to use it (as in the multiprocessing example). If you can’t get rid of global, then create a minimal code example and ask a separate question: “how to get rid of global by doing X”


Answer 2, authority 55%

The global statement is used where it is necessary to explicitly indicate that an object from the global scope (module namespace or globals dictionary) should be used and overrides the standard search mechanism for a variable (LEGB ), additionally makes it possible to modify an object outside its scope. requires discipline in general, since if before the declaration of global a in the nested scope of the name a was not in the OB globals () it will be created at the first assignment and will not disappear at the end of work (for example, a function).

dir ()
# ['__builtins__']
def foo ():
  global a
  a = 22
  pass
dir ()
# ['__builtins__', 'foo']
# foo needs to be called.
foo ()
dir ()
# ['__builtins__', 'a', 'foo']
a
# 22
# and now lives in globals ()
def foo1 ():
  print (a)
foo1 ()
# 22
# by LEGB rule name a was found in globals ()
def foo2 ():
  a + = 4
  pass
foo2 ()
# Traceback (most recent call last):
# File "& lt; input & gt;", line 1, in & lt; module & gt;
# File "& lt; input & gt;", line 2, in foo2
# UnboundLocalError: local variable 'a' referenced before assignment
# it is forbidden to change variables outside their scope for this
# you first need to specify that you need to change exactly a from globals ()
def foo3 ():
  global a
  a + = 4
foo3 ()
a
# 26

Answer 3, authority 36%

You need to specify a global variable directly in the body of the function at the very beginning, for example:

x = 1
def set_value ():
  global x
  x = 2
print (x)
& gt; & gt; & gt; 1
set_value ()
print (x)
& gt; & gt; & gt; 2

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions