Microsoft MVP성태의 닷넷 이야기
스크립트: 52. 파이썬 3.x에서의 동적 함수 추가 [링크 복사], [링크+제목 복사],
조회: 10236
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

파이썬 3.x에서의 동적 함수 추가

지난 글에 다룬,

파이썬 2.x에서의 동적 함수 추가
; https://www.sysnet.pe.kr/2/0/13379

코드를 Python 3.x 환경에서 실습해 봅니다. ^^




우선, 전역 함수를 클래스로 가져오는 것은 파이썬 3.x에서도 동일하게 다룰 수 있습니다.

def f_instance(self, arg):
    print('f_instance', self, arg)

def f_static(arg):
    print('f_static', arg)

def f_class(cls, arg):
    print('f_class', cls, arg)

class MyObject:
    def __init__(self):
        pass

MyObject.fi = f_instance
MyObject.fs = staticmethod(f_static)
MyObject.fc = classmethod(f_class)

myobj = MyObject()

myobj.fi('test1') 
myobj.fs('test2') 
myobj.fc('test3') 

print(type(MyObject.fi))
print(type(MyObject.fs))
print(type(MyObject.fc))

/* 출력 결과
f_instance <__main__.MyObject object at 0x7fa443db9970> test1
f_static test2
f_class <class '__main__.MyObject'> test3

<class 'function'>
<class 'function'>
<class 'method'>
*/

또한, 인스턴스 함수의 경우에 대해 types 모듈에 구현된 MethodType을,

# types.py (python 3.8)

# ...[생략]...

class _C:
    def _m(self): pass
MethodType = type(_C()._m)  # 동일한 역할을 했던 UnboundMethodType은 삭제됨

# ...[생략]...

경유해 구현하는 것도 동일한데요, 단지 차이점은 2개의 인자만 받는다는 점과 클래스 함수까지 재정의할 수 있어서 다음과 같은 코드가 가능합니다.

from types import MethodType

def f_instance(self, arg):
    print('f_instance', self, arg)

def f_class(cls, arg):
    print('f_class', cls, arg)

class MyObject:
    def __init__(self):
        pass

myobj = MyObject()
myobj.fi = MethodType(f_instance, myobj)  # 인스턴스 함수인 경우

MyObject.fc = MethodType(f_class, MyObject)  # 클래스 함수인 경우

myobj.fi('test')  # f_instance <__main__.MyObject object at 0x7f3a386fab50> test
myobj.fc('test2')  # f_class <class '__main__.MyObject'> test2

obj2 = MyObject()
obj2.fi('test3')  # (당연히) 예외 발생 AttributeError: 'MyObject' object has no attribute 'fi'
obj2.fc('test4')  # f_class <class '__main__.MyObject'> test4




다른 클래스로부터 가져오는 것도 파이썬 2.x와 비교해 다소 바뀐 점이 있습니다. 2.x에서는 정적 함수만 직관적인 동작을 했는데, 3.x부터는 인스턴스와 정적 함수가 모두 의도한 동작을 하게 됩니다.

class D:
    def __init__(self):
        pass

    def f_instance(self, arg):
        print( 'D.f_instance', self, arg)

    @staticmethod
    def f_static(arg):
        print( 'D.f_static', arg)

    @classmethod
    def f_class(cls_d, cls_my, arg):
        print( 'D.f_class', cls_d, cls_my, arg)


class MyObject:
    def __init__(self):
        pass

MyObject.fi = D.f_instance
MyObject.fs = staticmethod(D.f_static)
MyObject.fc = classmethod(D.f_class)

myobj = MyObject()

myobj.fi('test1')  # D 타입에 정의된 함수지만 self는 myobj 인스턴스가 전달됨
myobj.fs('test2')
myobj.fc('test3')  # 2.x에서와 마찬가지로 class를 받는 인자 2개가 필요


/* 출력 결과
D.f_instance <__main__.MyObject object at 0x7f238dae3970> test1
D.f_static test2
D.f_class   test3
*/

그런데, 과연 D 클래스에 정의된 함수에 MyObject 타입의 인스턴스가 넘어가는 것이 올바른 걸까요? 어찌 보면 이게 더 이상한 동작일 수 있습니다. 그래서 이번에는 오히려 D 인스턴스를 넘겨주기 위해 우회 방법을 사용해야 하는데요,

from functools import partial
from types import MethodType

class D:
    def __init__(self):
        pass

    def fi(self, arg):
        print('D.fi', self, arg)

class MyObject:
    def __init__(self):
        self.proxy = D()

def call_proxy(name, self, *args):
    return getattr(self.proxy, name)(*args)

method_name = 'fi'
p = partial(call_proxy, method_name)
p.__name__ = method_name
p.__doc__ = getattr(D, method_name).__doc__
m = MethodType(p, MyObject)
setattr(MyObject, method_name, m)

myobj = MyObject()

myobj.fi('test1')  # 예외 발생
/*
Traceback (most recent call last):
  File "test.py", line 30, in 
    myobj.fi('test1')
  File "test.py", line 18, in call_proxy
    return getattr(self.proxy, name)(*args)
AttributeError: type object 'MyObject' has no attribute 'proxy'
*/

이번엔 예외가 발생합니다. 이유는, 바뀐 MethodType 타입의 동작 때문입니다. 위에서 MethodType(p, MyObject)로 "클래스 MyObject"를 전달했기 때문에 call_proxy에 넘겨진 self는 MyObject의 인스턴스가 아닌 클래스 자체의 타입입니다.

def call_proxy(name, cls, *args):
    return getattr(cls.proxy, name)(*args)

즉, 클래스 수준에서는 proxy 멤버가 없기 때문에 "AttributeError: type object 'MyObject' has no attribute 'proxy'" 예외가 발생하는 것은 당연한 결과입니다. 따라서 3.x에서는 다른 클래스로부터 가져온 인스턴스 함수는 현실적으로 정상 동작을 할 수 없게 됩니다.




아마도 저런 제약이 문제가 된 것인지, 파이썬 3.x의 socket 모듈은 구현 방식이 바뀌었습니다. 기존에는 _socket 모듈의 socket 타입에 있는 함수를 병합하는 방식이었지만, 3.x에서는 _socket.socket으로부터 상속해 구현하고 있습니다.

class socket(_socket.socket):

    """A subclass of _socket.socket adding the makefile() method."""

    __slots__ = ["__weakref__", "_io_refs", "_closed"]

    def __init__(self, family=-1, type=-1, proto=-1, fileno=None):
        # ...[생략]...

    def dup(self):
        # ...[생략]...

    def accept(self):
        # ...[생략]...

    def makefile(self, mode="r", buffering=None, *,
        # ...[생략]...

    def _sendfile_use_send(self, file, offset=0, count=None):
        # ...[생략]...

    def _check_sendfile_params(self, file, offset, count):
        # ...[생략]...

    def sendfile(self, file, offset=0, count=None):
        # ...[생략]...

    def _decref_socketios(self):
        # ...[생략]...

    def _real_close(self, _ss=_socket.socket):
        # ...[생략]...

    def close(self):
        # ...[생략]...

    def detach(self):
        # ...[생략]...

    @property
    def family(self):
        # ...[생략]...

    @property
    def type(self):
        # ...[생략]...

    # ...[생략]...

덕분에 (2.x에서는 문제가 되었지만) connect 함수 등의 qualname을 구하는 것이 가능합니다.

import socket

print(socket.socket.accept.__qualname__)
print(socket.socket.connect.__qualname__)  # 2.x에서는 qualname을 이용해도 오류

기타 시간되시면 다음의 Q&A 글도 한번 읽어보시고. ^^

Adding a method to an existing object instance in Python
; https://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object-instance-in-python





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/24/2023]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13693정성태7/24/20247244개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
13692정성태7/24/20248025디버깅 기술: 199. Windbg - 리눅스에서 뜬 닷넷 응용 프로그램 덤프 파일에 포함된 DLL의 Export Directory 탐색
13691정성태7/23/20247385디버깅 기술: 198. Windbg - 스레드의 Win32 Message Queue 정보 조회
13690정성태7/23/20247019오류 유형: 919. Visual C++ 리눅스 프로젝트 - error : ‘u8’ was not declared in this scope
13689정성태7/22/20248516디버깅 기술: 197. Windbg - PE 포맷의 Export Directory 탐색
13688정성태7/21/20247630닷넷: 2281. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리파일 다운로드1
13687정성태7/19/20248060닷넷: 2280. C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법파일 다운로드1
13686정성태7/19/20247855오류 유형: 918. Visual Studio - ATL Simple Object 추가 시 error C2065: 'IDR_...': undeclared identifier
13685정성태7/19/20248002스크립트: 66. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법 - 두 번째 이야기
13684정성태7/19/20248179닷넷: 2279. C# - 문자열 보간식 사례 (예: 조건 연산자 사용)
13683정성태7/18/20247651오류 유형: 917. ClrMD - Linux 환경의 .NET 5 덤프 분석 시 hang 현상
13682정성태7/18/20247869닷넷: 2278. WPF - 스레드에 종속되는 DependencyObject파일 다운로드1
13681정성태7/17/20247471닷넷: 2277. C# 13 - (2) 메서드 그룹의 자연 타입 개선 (메서드 추론 개선)파일 다운로드1
13680정성태7/16/20247846닷넷: 2276. C# - Method Group, Natural Type, function_type파일 다운로드1
13679정성태7/16/20246934Linux: 76. Linux - C++ (getaddrinfo 등을 담고 있는) libnss 정적 링크
13678정성태7/15/20247065VS.NET IDE: 191. Visual Studio 2022 - .NET 5 프로젝트를 Docker Support로 실행했을 때 오류
13677정성태7/15/20247148오류 유형: 916. MSBuild - CheckEolTargetFramework (warning NETSDK1138)
13676정성태7/14/20247326Linux: 75. gdb에서 glibc의 함수에 Breakpoint 걸기
13675정성태7/13/20249117C/C++: 166. C/C++ - DLL에서 template 함수를 export하는 방법 [1]파일 다운로드1
13674정성태7/13/20248000오류 유형: 915. Unhandled Exception: Microsoft.Diagnostics.NETCore.Client.ServerNotAvailableException: Unable to connect to Process
13673정성태7/11/20248442닷넷: 2275. C# 13 - (1) 신규 이스케이프 시퀀스 '\e'파일 다운로드1
13672정성태7/10/20247152닷넷: 2274. IIS - (프로세스 종료 없는) AppDomain Recycle
13671정성태7/10/20247261오류 유형: 914. Package ca-certificates is not installed.
13669정성태7/9/20247381오류 유형: 913. C# - AOT StaticExecutable 정적 링킹 시 빌드 오류
13668정성태7/8/20247394개발 환경 구성: 716. Hyper-V - Ubuntu 22.04 Generation 2 유형의 VM 설치
13667정성태7/7/20246621닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...