두 번째 Python 기초 파트 정리. 오늘은 변수의 범위(scope)에 대해서 정리를 할 건데, 사실 이건 코드를 작성하는 사람이 알잘딱깔센하여 주의해서 사용해야 한다고 생각하고 있다.
코딩을 배웠다면 너무나 자연스러운 개념이라서 한 번도 깊게 생각해 본 적은 없었는데, 배운 김에 정리를 해보려고 한다.
변수의 scope, 파이썬이 변수를 읽어나가는 순서
우선 Python은 변수를 찾아 나갈 때 LEGB Rule을 따른다.
* How Python search the variable? (LEGB rule)
1. local
2. enclosing
3. global
4. built-in
즉, local 변수에서 가장 먼저 찾고, 그게 아니라면 바로 윗 단계에 있는 enclosing variable. 그리고 global, 마지막으로 built-in 변수를 찾아 나선다.
built-in 변수는 print(dir(__builtins__)) 를 통해서 어떤 게 있는지 확인할 수 있다.
직접 찾아보니까 이렇게나 많은 built-in 변수들이 있다.
global 키워드 사용법
아래 코드를 살펴보자.
my_score = 50
## global keyword
def inside_value_function():
global my_score
my_score = 80
print(f"my score inside is {my_score}")
inside_value_function()
print(f"my score outside is {my_score}")
첫 번째로 함수 바깥에서 정의된 my_score 변수에 50을 넣는다.
그리고 함수 안에서 global 키워드로 'global my_score'라고 쓴다.
이렇게 되면 my_score 변수를 global로 사용하겠다는 뜻이 된다.
my_score에 80을 다시 할당했지만 아무런 에러 없이 다음과 같은 결과가 나타난다.
두 개의 print문 모두 80으로 출력되었음을 확인할 수 있다.
즉, 함수 안에서 전역 변수인 my_score의 값을 바꾸어 주었음을 알 수 있다.
global keword가 없다면 어떻게 될까?
my_score = 50
## global keyword
def inside_value_function():
my_score = 80
print(f"my score inside is {my_score}")
inside_value_function()
print(f"my score outside is {my_score}")
함수 안에서 my_score라는 local 변수를 또다시 만들어서 80이라는 값을 할당했다.
print 문의 결과는?
80과 50이 나온다. 두 my_score는 이름만 같을 뿐 서로 다른 name space를 가지고 있기 때문이다.
nonlocal 키워드
nonloacl 키워드는 아래와 같이 함수가 여러 개 중첩되어 있을 때 유용하다.
def first_function():
first_value = 10
def second_function():
first_value = 20
second_function()
print(first_value)
first_function()
위의 코드를 실행하면, second_function을 실행하였음에도 불구하고 값은 10이 그대로 나타난다.
second_function이 first_function안에 있는 first_value라는 변수에 접근할 수 없는, 서로 다른 name space를 가진 별도의 변수이기 때문.
def first_function():
first_value = 10
def second_function():
nonlocal first_value
first_value = 20
second_function()
print(first_value)
first_function()
하지만 위와 같이 nonlocal keyword를 사용해서 first_value에 적용해 주면, 가장 가까운 scope에 있는 first_value 변수를 사용할 수 있게 된다.
당연하게도, 위의 출력 값은 20이 된다.
여기까지, 간단하게 변수의 scope와 global / nonlocal 키워드 사용법에 대해서 정리해 보았다.
솔직히 얼마나 자주 쓸 수 있을지는 모르겠지만, 중요한 개념이니까 기억해 두려고 썼다.
'Pyhon 기초, 실전' 카테고리의 다른 글
[Python 기초] list, dictionary comprehension and conditional comprehension (1) | 2023.07.17 |
---|---|
[Python 기초] 여러 가지 파일 읽고 쓰기 (txt, csv, pickle, json 등) (0) | 2023.07.16 |
[Python 기초] set과 tuple 그리고 tuple의 packing, unpacking (0) | 2023.07.14 |
[Python 기초] 주석(Docstring) 작성 스타일 (0) | 2023.07.13 |
[Python 기초] copy & assignment: shallow copy, deep copy (얕은 복사, 깊은 복사) (0) | 2023.07.09 |