내 프로젝트 모듈과 동일 이름의 라이브러리 모듈 사용하기
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How can I import from the standard library, when my project has a module with the same name? (How can I control where Python looks for modules?)
내 프로젝트에 모듈 이름과 같은 이름의 모듈이 있을 때, 표준 라이브러리에서 import하는 방법은 무엇인가요? (Python에서 모듈을 검색하는 위치를 제어하는 방법은 무엇인가요?)
문제 내용
There is a module in my project folder called calendar
. Elsewhere in the code, I would like to use the standard library Calendar
class. But when I try to import this class, using from calendar import Calendar
, this imports from my own module instead, causing errors later.
저의 프로젝트 폴더에 calendar라는 모듈이 있습니다. 코드 다른 부분에서 표준 라이브러리 Calendar 클래스를 사용하고 싶은데, from calendar import Calendar를 사용하여 이 클래스를 가져오려고 하면 제 프로젝트 모듈에서 가져와서 나중에 오류가 발생합니다. 이런 경우 어떻게 하면 될까요?
How can I avoid this? Do I have to rename the module?
이것을 어떻게 피할 수 있나요? 모듈 이름을 바꿔야 하나요?
높은 점수를 받은 Solution
It's not necessary to rename the module. Instead, in Python 2.5 and above, use absolute_import
to change the importing behavior.
모듈 이름을 바꾸는 것은 필요하지 않습니다. 대신 Python 2.5 이상에서는 absolute_import를 사용하여 가져오기 동작을 변경할 수 있습니다.
For example, to import the standard library socket
module, even if there is a socket.py
in the project:
예를 들어, 프로젝트에 socket.py가 있는 경우에도 표준 라이브러리 socket 모듈을 가져오려면 다음과 같이 절대 경로 임포트를 사용할 수 있습니다:
from __future__ import absolute_import
import socket
In Python 3.x, this behaviour is the default. Pylint will complain about the code, but it's perfectly valid.
Python 3.x에서는 이러한 동작이 기본값입니다. Pylint는 코드에 대해 불평할 수 있지만, 이것은 완벽하게 유효합니다.
가장 최근 달린 Solution
In Python 3.5 and up, use the standard library importlib
module to import directly from a specified path, bypassing import
's lookup mechanism:
Python 3.5 이상에서는, import의 검색 메커니즘을 우회하여 지정된 경로에서 직접 가져오기 위해 표준 라이브러리 importlib 모듈을 사용합니다.
import importlib.util
import sys
# For illustrative purposes.
import tokenize
file_path = tokenize.__file__ # returns "/path/to/tokenize.py"
module_name = tokenize.__name__ # returns "tokenize"
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
In actual code, file_path
can be set to any path to a .py
file to import; module_name
should be the name of the module that will be imported (the name that the import system uses to look up the module when further import
statements are attempted). Subsequent code will use module
as the name of the module; change the variable name module
to use a different name.
실제 코드에서, file_path는 가져올 .py 파일의 경로로 설정할 수 있으며, module_name은 가져올 모듈의 이름이어야 합니다(추가적인 import 문이 시도될 때 import 시스템에서 모듈을 검색하는 데 사용하는 이름). 이후 코드에서 모듈 이름은 module로 사용됩니다. 변수 이름 module을 다른 이름으로 변경하여 사용할 수 있습니다.
To load a package instead of a single file, file_path
should be the path to the package's root __init__.py
.
단일 파일 대신 패키지를 로드하려면, file_path는 패키지의 루트 **init**.py 경로여야 합니다.
출처 : https://stackoverflow.com/questions/6031584/how-can-i-import-from-the-standard-library-when-my-project-has-a-module-with-th