Python scope between local and global

I have two samples:

One:

import math

def my_function():
    print(math.pi)
    math.pi = 3
    print(math.pi)

my_function()

Conclusion:

3.141592653589793
3

Two:

a = 0

def my_function():
    print(a)
    a = 3
    print(a)

my_function()

Conclusion:

UnboundLocalError: local variable 'a' referenced before assignment

So what is the difference between the two? I thought that both math.piand aare global in this case, and it should produce UnboundLocalError.

+4
source share
3 answers

If you perform the assignment of a variable inside a function, the global variable will be ignored and will not be available when the function is executed, in the sample with mathlib you do not redefine the name math, so it works. Snipped below will give you the same error with math lib:

import math

def my_function():
  print(math.pi)
  math = 1

my_function()

global , - , .

import math


def my_function():
  global math
  print(math.pi)
  math = 1

print(math) # -> <module 'math' from ...    
my_function() # -> 3.14159265359
print(math) # -> 1
+3

math, math.pi. math, . - , .

def my_function():
    print(math.pi)
    math = 3
    print(math.pi)

​​ , :

UnboundLocalError: 'math',

+1

SO.

, , . a = 3 a . print(a) , .

This is why you see:

UnboundLocalError: local variable 'a' referenced before assignment.

The global instance created a = 0does not play any role here.

0
source

Source: https://habr.com/ru/post/1688425/


All Articles