[TIL] name space

양희연·2020년 8월 24일
0

Python

목록 보기
9/10
post-thumbnail

지난 scope 포스트에서 살펴본 바와 같이 파이썬에서는 특정 변수나 함수가 갖고 있는 범위가 중요하다. 이에 따라 코딩하는 결과값이 달라질 수도 있기 때문이다.

이번에 살펴볼 name space도 비슷하다.

💡 A namespace is a mapping from names to objects.

변수에 객체를 할당하면, 변수와 변수에 연결된 객체는 딕셔너리 형태로 연결되어 네임스페이스 안에 저장된다.



🛫 전역 네임스페이스

a = 1

#전역 네임스페이스 확인하는 함수: globals()
print(globals())

#결과값
{'__name__': '__main__', '__doc__': None, '__package__': None, 
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {}, 
'__builtins__': <module 'builtins' (built-in)>, 
'__file__': '/Users/user/Desktop/test.py',
'a': 1}

🚖 지역 네임스페이스

a = 1

def func():
    a = 10
    b = 20
    #지역 네임스페이스 확인하는 함수: locals()
    print('함수 내부 namespace: ', locals())

func()
print(globals())

#결과값
함수 내부 namespace:  {'a': 10, 'b': 20}
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>,
'__file__': '/Users/user/Desktop/test.py',
'a': 1, 'func': <function func at 0x7f963bf4f430>}
profile
꾸준히 나아가자!

0개의 댓글