Computer Engineering/Python

파이썬 import time과 run time / 임포트 타임과 런타임 이해하기

jordan.bae 2023. 7. 16. 15:41

파이썬에서 import time과 runtime은 코드가 실행되는 시점에 대한 개념입니다.

import time은 파이썬 모듈이 import 될 때 실행되는 코드들을 의미하고, run time은 실제 해당 함수나 클래스가 호출됐을 때 실행되는 것을 의미합니다. 이 두 개념을 이해하는 것은 코드를 작성할 때 runtime에 결정되는 변수를 import time에 실행되는 코드에 포함하면 에러가 발생할 수 있는데 이를 이해하는데 도움이 되고, 마찬가지인 개념에서 circular import 문제를 이해하는데도 도움이 됩니다.

 

import time (임포트 타임)

import time에 실행되는 코드

  • 임포트 타임(import time)은 해당 모듈을 임포트하는 동안에 실행되는 코드로, 주로 모듈 초기화 작업이나 전역 변수, 함수, 클래스 등을 정의하는 부분입니다.
  • import time에 실행되는 부분 중 decorator 또한 import time에 실행됩니다.

예제 코드

# module.py
print("This code is executed during import")

def my_function():
    print("This function is defined during import")

def my_decorator(func):
    print("This is executed during import time.")

    def wrapper(*args, **kwargs):
        print("This is executed during runtime.")
        result = func(*args, **kwargs)
        return result

    return wrapper


class Human:
  print("I AM HUMAN")

	def __init__(name: str):
    self.name = name
# main.py
import module


@module.my_decorator
def runtime_func()
		print("this is runtime)
  1. 위의 예시 코드에서 **import module**을 수행하면 "This code is executed during import"와 "I AM HUMAN" 그리고 "This is executed during import time." 가 **import module**을 실행하는 시점에 모듈 전체가 로드되고 print() 함수가 호출되기 때문입니다.
  2. runtime_func 안의 안에 코드는 my_function 함수를 실행해야만 실행됩니다.

 

Runtime (런타임)

런타임은 모듈이 이미 임포트되었을 때 해당 모듈 내의 함수, 클래스 등을 호출하는 시점을 말합니다. 런타임에서는 모듈의 함수 또는 클래스를 사용하여 원하는 작업을 수행하거나 모듈에 접근할 수 있습니다.

# modules.py

print("This is executed during import time.")

def my_function():
    print("This is executed during runtime.")
# main.py
import module

print("This is executed during runtime.")

module.my_function()

python main.py 실행 결과:

This is executed during import time. This is executed during runtime. This is executed during runtime.

위의 예시에서 module.py는 모듈 파일이며, 임포트 타임에 "This is executed during import time."이 출력됩니다. 이후 main.py에서 모듈을 임포트하면 "This is executed during runtime."이 출력되고, module.my_function()을 호출하여 "This is executed during runtime."이 추가로 출력됩니다. 이렇게 모듈의 함수 호출은 런타임에 실행되는 것을 확인할 수 있습니다.

따라서 모듈을 임포트할 때와 런타임에 실행되는 코드는 서로 다르며, 이를 이해하여 파이썬 프로그램을 작성할 수 있습니다.

 

임포트 타임에 실행되는 코드 작성시 주의 할 점

임포트 타임에 실행되는 코드를 작성할 때 runtime에 결정되는 변수나 값을 써서 오류가 발행할 수 있습니다.

적절한 예시가 생각나지는 않아서 한 가지 인위적인 예를 들어보면 config.py 에 여러 환경 변수가 있는데 test 환경을 위한 환경 변수가 없다고 하면 config 모듈을 import 되는 코드만으로도 에러가 발생할 수 있습니다.

코드 예제

# utils.py

import config


def add(x: int , y: int) -> int:
		return x + y


# config.py
import boto3

ssm = boto3.client("ssm")
response = ssm.get_parameter(Name="/db_1/db_user", WithDecryption=True)
db_user = response["Parameter"]["Value"]
# test_utils.py
import unittest

from utils import add

class TestUtils(unittest.TestCase):
    def setUp(self):
        pass

    def test_add(self):
        x, y = 1, 3
		    expected = 4
        result = add(x, y)
        self.assertEqual(result, expected_

test 코드에 config를 필요로 하는 경우 import time에 ssm에 접근하려고 하는데 secret이 설정되어 있지 않아서 에러가 발생합니다. 물론 utils에서 config에 접근하는 것이 올바른 설계가 아니지만 예시를 위해서 상황을 만들어봤습니다.

 

기타

circular import 문제도 역시 발생할 수 있습니다. 해당 문제에 대해서는 다른 블로그에 잘 정리된 글이 있어 궁금하신 분들은 읽어보시길 추천드립니다.

 

Python Circular Imports

Python Circular Imports가 무엇이며, 오류는 어떻게 해결할까?

blog.mathpresso.com

 

마무리

작성한 파이썬 코드가 언제 실행되는지 이해하는 것은 작성된 코드가 어떻게 실행되는지 이해할 수 있기 때문에 중요합니다. 또, 이 때문에 발생할 수 있는 문제를 쉽게 발견하고 미리 예방할 수 있습니다.

반응형