Microsoft MVP성태의 닷넷 이야기
스크립트: 52. 파이썬 3.x에서의 동적 함수 추가 [링크 복사], [링크+제목 복사],
조회: 10237
글쓴 사람
정성태 (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)
13768정성태10/15/20245395C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
13767정성태10/14/20244768오류 유형: 929. bpftrace 수행 시 "ERROR: Could not resolve symbol: /proc/self/exe:BEGIN_trigger"
13766정성태10/14/20244552C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작파일 다운로드1
13765정성태10/12/20245261오류 유형: 928. go build 시 "package maps is not in GOROOT" 오류
13764정성태10/11/20245626Linux: 85. Ubuntu - 원하는 golang 버전 설치
13763정성태10/11/20244985Linux: 84. WSL / Ubuntu 20.04 - bpftool 설치
13762정성태10/11/20245009Linux: 83. WSL / Ubuntu 22.04 - bpftool 설치
13761정성태10/11/20244914오류 유형: 927. WSL / Ubuntu - /usr/include/linux/types.h:5:10: fatal error: 'asm/types.h' file not found
13760정성태10/11/20245448Linux: 82. Ubuntu - clang 최신(stable) 버전 설치
13759정성태10/10/20246363C/C++: 177. C++ - 자유 함수(free function) 및 주소 지정 가능한 함수(addressable function) [6]
13758정성태10/8/20245578오류 유형: 926. dotnet tools를 sudo로 실행하는 경우 command not found
13757정성태10/8/20245514닷넷: 2306. Linux - dotnet tool의 설치 디렉터리가 PATH 환경변수에 자동 등록이 되는 이유
13756정성태10/8/20245624오류 유형: 925. ssh로 docker 접근을 할 때 "... malformed HTTP status code ..." 오류 발생
13755정성태10/7/20246022닷넷: 2305. C# 13 - (9) 메서드 바인딩의 우선순위를 지정하는 OverloadResolutionPriority 특성 도입 (Overload resolution priority)파일 다운로드1
13754정성태10/4/20245573닷넷: 2304. C# 13 - (8) 부분 메서드 정의를 속성 및 인덱서에도 확대파일 다운로드1
13753정성태10/4/20245593Linux: 81. Linux - PATH 환경변수의 적용 규칙
13752정성태10/2/20246272닷넷: 2303. C# 13 - (7) ref struct의 interface 상속 및 제네릭 제약으로 사용 가능 [6]파일 다운로드1
13751정성태10/2/20245402C/C++: 176. C/C++ - ARM64로 포팅할 때 유의할 점
13750정성태10/1/20245293C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계
13749정성태9/30/20245535닷넷: 2302. C# - ssh-keygen으로 생성한 Private Key와 Public Key 연동파일 다운로드1
13748정성태9/29/20245743닷넷: 2301. C# - BigInteger 타입이 byte 배열로 직렬화하는 방식
13747정성태9/28/20245590닷넷: 2300. C# - OpenSSH의 공개키 파일에 대한 "BEGIN OPENSSH PUBLIC KEY" / "END OPENSSH PUBLIC KEY" PEM 포맷파일 다운로드1
13746정성태9/28/20245685오류 유형: 924. Python - LocalProtocolError("Illegal header value ...")
13745정성태9/28/20245545Linux: 80. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (lldb)
13744정성태9/27/20245974닷넷: 2299. C# - Windows Hello 사용자 인증 다이얼로그 표시하기파일 다운로드1
13743정성태9/26/20246427닷넷: 2298. C# - Console 프로젝트에서의 await 대상으로 Main 스레드 활용하는 방법 [1]
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...