Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

파이썬 - 'urllib.request' 모듈의 명시적/암시적 로딩 차이

(파이썬 2 환경은 잊기로 하고) 기본 파이썬 환경에서는 urllib.request 모듈은 로딩돼 있지 않는데요, 즉 sys.modules에 등록돼 있지 않습니다.

$ python3
Python 3.8.10 (default, Mar 18 2025, 20:04:55)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.modules['urllib.request'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'urllib.request'
>>>

$ cat main.py
import sys

print(sys.modules['urllib.request'])  

$ python3 main.py
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(sys.modules['urllib.request'])
KeyError: 'urllib.request'

하지만, urllib.request 모듈을 로드하도록 유발하는 코드가 파이썬 내부에서 심심치 않게 실행되므로 이에 따른 부작용(side-effect)를 감안해야 합니다. 가령, 단순히 오류만 발생했어도,

$ python3
Python 3.8.10 (default, Mar 18 2025, 20:04:55)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> t   # 이 코드의 실행으로 오류 처리하는 과정에서 urllib.request 모듈이 로드됨
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 't' is not defined
>>> import sys
>>> print(sys.modules['urllib.request'])
<module 'urllib.request' from '/usr/lib/python3.8/urllib/request.py'>

저런 식으로 urllib.request 모듈이 로딩되기도 합니다.




'urllib.request' 모듈에는 또 다른 특별함이 하나 더 있는데요, __import__('...') 함수와,

import sys

lm = __import__('urllib.request')  # 여기서는 'urllib.request' 이름으로 로딩했지만,

print(lm)
print(sys.modules['urllib'])  # sys.modules에는 'urllib' 이름으로 등록되고, 그 경로는 ./urllib/__init__.py
print(sys.modules['urllib.request']) # 오히려 동일한 이름으로는 ./urllib/request.py라는 다른 모듈이 등록됨

''' 실행 결과
$ python3 main.py
<module 'urllib' from '/usr/lib/python3.8/urllib/__init__.py'>
<module 'urllib' from '/usr/lib/python3.8/urllib/__init__.py'>
<module 'urllib.request' from '/usr/lib/python3.8/urllib/request.py'>
'''

import '...'에 의한 로딩 차이가 있다는 점입니다.

import sys

print(sys.modules.get('urllib.request'))  # 'urllib.request' 이름으로 등록돼 있지 않은 것을 확인,

import urllib.request                 # import 문에 의해 로딩된 것은 'urllib.request' 이름으로 등록됨
print(sys.modules['urllib.request'])  # 따라서 'urllib.request' 이름으로 모듈이 존재하고,
                                      # 그 경로는 ./urllib/request.py
8
''' 실행 결과
$ python3 main.py
None
<module 'urllib.request' from '/usr/lib/python3.8/urllib/request.py'>
'''

__import__처럼 동적으로 로딩을 원하는데 import 구문과 유사한 동작을 원한다면 그나마 importlib.import_module가 더 나은 후보입니다.

import sys
import importlib

lm = importlib.import_module('urllib.request')

print(lm)  # 출력 결과: <module 'urllib.request' from '/usr/lib/python3.8/urllib/request.py'>
print(sys.modules['urllib.request'])  # 출력 결과: <module 'urllib.request' from '/usr/lib/python3.8/urllib/request.py'>

파이썬의 역사가 오래된 만큼, 여러 가지 이유로 인해 추가됐던 유사한 기능들의 세세한 차이를 이제 와서 이해하기란 어려운 것 같습니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 5/20/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  [26]  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13305정성태4/1/202313634Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전) [1]파일 다운로드1
13304정성태3/31/202313955VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/202312158Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/202312993Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/202313481Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션 [1]파일 다운로드1
13300정성태3/28/202312667Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/202312487Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/202312267Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/202313848Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/202312936Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/202313047Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/202313015.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/202312456오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/202313138Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/202313295.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/202313189.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/202312122Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/202312372Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/202312366Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/202312799Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/202312133Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법 [2]파일 다운로드1
13284정성태3/13/202311951Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/202310473오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/202310882Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/202311778Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/202313479개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
... 16  17  18  19  20  21  22  23  24  25  [26]  27  28  29  30  ...