본문 바로가기
Python/Python FAQ

Python 몽키 패칭이란 무엇인가요?, What is monkey patching?

by 베타코드 2023. 6. 30.
반응형

질문


나는 monkey patching 또는 monkey patch가 무엇인지 이해하려고 노력하고 있습니다.

이것은 메서드/연산자 오버로딩 또는 위임과 비슷한 것인가요?

이러한 것들과 어떤 공통점이 있을까요?


답변


No, it's not like any of those things. It's simply the dynamic replacement of attributes at runtime.

For instance, consider a class that has a method get_data. This method does an external lookup (on a database or web API, for example), and various other methods in the class call it. However, in a unit test, you don't want to depend on the external data source - so you dynamically replace the get_data method with a stub that returns some fixed data.

Because Python classes are mutable, and methods are just attributes of the class, you can do this as much as you like - and, in fact, you can even replace classes and functions in a module in exactly the same way.

But, as a commenter pointed out, use caution when monkeypatching:

  1. If anything else besides your test logic calls get_data as well, it will also call your monkey-patched replacement rather than the original -- which can be good or bad. Just beware.

  2. If some variable or attribute exists that also points to the get_data function by the time you replace it, this alias will not change its meaning and will continue to point to the original get_data. (Why? Python just rebinds the name get_data in your class to some other function object; other name bindings are not impacted at all.)

반응형

댓글