Skip to content

Instantly share code, notes, and snippets.

@makerj
Last active February 10, 2016 04:59
Show Gist options
  • Save makerj/8c79da1fe2cbea6cf102 to your computer and use it in GitHub Desktop.
Save makerj/8c79da1fe2cbea6cf102 to your computer and use it in GitHub Desktop.
#Python global variable

#Python global variable 이곳 저곳 참고했다.

SyntaxWarning: name '변수명' is assigned to before global declaration

뭐 결론부터 말하자면 이렇다 if, while, for, try새 블록을 만들지 않는다. 즉 새 local scope를 만들지 않기 때문에 여전히 글로벌인 것이고, 쓸 데 없이 global을 선언해서 파이썬 인터프리터는 어리둥절행이 된 것이다.

주로 이런 일이 일어나는 경우 2가지를 정리해봤다. ###if name == 'main':

ret_code = 0

if __name__ == '__main__':
  global ret_code
  ret_code = 1234
  ...

그렇다. 많이 사용되는 코드다. if __name__ == '__main__': 이라고 얄짤없다. 어쨋든 if절이기 때문에 새 스코프가 생성되는 것이 아니다. 따라서 위의 코드는

ret_code = 0

if __name__ == '__main__':
  ret_code = 1234
  ...

로 변경되어야 한다.

###global의 남용

x = 0

def func(a, b, c):
    if a == b:
        global x
        x = 10
    elif b == c:
        global x
        x = 20

함수 안에서 global x가 두번이나 사용되었다. 한 번만 선언하자. 따라서 이 코드는 다음과 같이 변경되어야 한다:

x = 0

def func(a, b, c):
    global x
    if a == b:
        x = 10
    elif b == c:
        x = 20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment