Microsoft MVP성태의 닷넷 이야기
스크립트: 52. 파이썬 3.x에서의 동적 함수 추가 [링크 복사], [링크+제목 복사],
조회: 3491
글쓴 사람
정성태 (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)
13341정성태5/8/20234196닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234283오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20235119닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234491닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234980Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234812.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234828.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234460Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233898Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233968Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233954오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233644Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233885Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233503VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233915VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235414.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234683스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234499.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234444개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235264VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20234059개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233957개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234463개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234342개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234385오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233644오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...