Menu
CoddyTech

require에서 import로

Coddy의 Lua 개발자를 위한 Python 코스 레슨. 48개 중 29번째.

Lua의 require는 모듈을 불러오고 반환된 값을 캐시하며, 반환값은 흔히 테이블입니다. Python의 import는 일반적인 첫 import 때 모듈 본문을 실행하고 모듈 객체를 캐시에 보관합니다. Python 소스 파일은 import 문에서 .py 접미사를 빼고 모듈 이름으로 사용합니다. 메인 가드를 사용하면 import 중에 데모 입력/출력이 실행되지 않도록 할 수 있습니다. Lua 모듈의 반환 테이블과 달리 Python 모듈은 정의된 항목의 네임스페이스를 노출합니다.

Lua 예시

local arithmetic = {}
function arithmetic.twice(x) return x * 2 end
print(arithmetic.twice(4))

Python

def twice(x):
    return x * 2
def main():
    print(twice(4))
if __name__ == "__main__":
    main()

포팅 시 주의할 점

재사용 가능한 함수는 import 시점에 입력을 읽지 않도록 하세요. 다른 편집 가능 파일의 이름이 main.py여도 작업 실행기는 driver.py를 시작합니다.

편집 가능한 Python 파일에 지정된 API를 구현하세요. 잠긴 driver.py가 프로그램을 실행하고 입력/출력을 제공합니다. 해당 파일의 import와 이름은 변경하지 마세요.

challenge icon

챌린지

초급

import math를 사용하고, math.gcd(a, b)를 반환하는 함수 common_pack(a, b)와 별도의 줄에 입력된 음이 아닌 정수 두 개를 읽고 결과를 출력하는 main()을 포함한 완전한 프로그램을 작성하세요. math.gcd는 최대공약수를 반환합니다. 한쪽 인수가 0이면 다른 인수를 반환하고, 두 인수가 모두 0이면 0을 반환합니다. if __name__ == "__main__": 아래에서만 main()을 호출하세요. 정의를 가져올 때는 입력을 읽거나 출력하면 안 됩니다.

잠금된 테스트 하네스는 첫 번째 줄에서 script 또는 import를 읽습니다. 프로그램은 이 모드를 읽거나 처리하면 안 됩니다. 스크립트 모드에서 하네스는 __name__을 "__main__"으로 설정하고, 그러면 프로그램은 위에서 설명한 대로 입력을 읽고 출력합니다. 가져오기 모드에서는 program.py를 program 모듈로 가져오므로, 해당 파일에서 __name__ == "program"이 되고 정의를 불러오는 동안 입력이나 출력을 시도하면 오류가 발생합니다. 불러오기가 끝나면 하네스는 일반적인 입력 및 출력을 복원하고, 도우미 함수 호출 횟수와 음이 아닌 정수 두 개가 들어 있는 해당 개수만큼의 줄을 읽습니다. 그런 다음 각 쌍에 대해 재사용 가능한 도우미 함수를 호출하고, 각 쌍의 도우미 함수 결과를 한 줄에 출력합니다. 도우미 함수와 main 모두 메인 가드 바깥에 정의하세요. 완전한 Python 프로그램만 제출하면 됩니다. 하네스는 제공되며 수정할 수 없습니다.

program.py를 수정하세요. 잠금된 driver.py는 파일을 스크립트로 실행하는 경우와 모듈로 가져오는 경우를 모두 테스트합니다. 드라이버가 테스트 모드 입력을 처리하므로, 프로그램은 위에서 설명한 데이터만 읽으면 됩니다.

직접 해보기

import importlib as _coddy_importlib
import runpy as _coddy_runpy
import builtins as _coddy_builtins
_coddy_input = _coddy_builtins.input
_coddy_print = _coddy_builtins.print
_coddy_mode = _coddy_input()
_coddy_import_io = []
def _coddy_forbidden_input(*args, **kwargs):
    _coddy_import_io.append("input")
    raise AssertionError("input during module loading")
def _coddy_forbidden_print(*args, **kwargs):
    _coddy_import_io.append("print")
    raise AssertionError("print during module loading")
if _coddy_mode == "script":
    __name__ = "__main__"
elif _coddy_mode == "import":
    __name__ = "course_module"
    _coddy_builtins.input = _coddy_forbidden_input
    _coddy_builtins.print = _coddy_forbidden_print
else:
    raise AssertionError("invalid harness mode")

if _coddy_mode == "script":
    _coddy_namespace = _coddy_runpy.run_module("program", run_name="__main__")
else:
    _coddy_namespace = vars(_coddy_importlib.import_module("program"))
common_pack = _coddy_namespace['common_pack']
main = _coddy_namespace['main']
_coddy_builtins.input = _coddy_input
_coddy_builtins.print = _coddy_print
if _coddy_import_io:
    raise AssertionError("module loading attempted input or output")
if _coddy_mode == "import":
    if not callable(main):
        raise AssertionError("main must be a callable function")
    _coddy_count = int(_coddy_input())
    for _coddy_index in range(_coddy_count):
        _coddy_left, _coddy_right = _coddy_input().split()
        _coddy_result = common_pack(int(_coddy_left), int(_coddy_right))
        if type(_coddy_result) is not int:
            raise AssertionError("common_pack must return an integer")
        _coddy_print(_coddy_result)
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Lua 개발자를 위한 Python의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러