Microsoft MVP성태의 닷넷 이야기
스크립트: 52. 파이썬 3.x에서의 동적 함수 추가 [링크 복사], [링크+제목 복사],
조회: 10316
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12737정성태7/28/202114999오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/202115267오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/202115167.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202131986스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202119856.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/202113309오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/202115345개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/202116775개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/202115257.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
12728정성태7/22/202115290.NET Framework: 1079. MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
12727정성태7/21/202116469.NET Framework: 1078. C# 단위 테스트 - MSTestv2/NUnit의 Assert.Inconclusive 사용법(?) [1]
12726정성태7/21/202116244VS.NET IDE: 169. 비주얼 스튜디오 - 단위 테스트 선택 시 MSTestv2 외의 xUnit, NUnit 사용법 [1]
12725정성태7/21/202114710오류 유형: 741. Failed to find the "go" binary in either GOROOT() or PATH
12724정성태7/21/202117600개발 환경 구성: 582. 윈도우 환경에서 Visual Studio Code + Go (Zip) 개발 환경 [1]
12723정성태7/21/202114512오류 유형: 740. SharePoint - Alternate access mappings have not been configured 경고
12722정성태7/20/202114267오류 유형: 739. MSVCR110.dll이 없어 exe 실행이 안 되는 경우
12721정성태7/20/202115427오류 유형: 738. The trust relationship between this workstation and the primary domain failed. - 세 번째 이야기
12720정성태7/19/202114682Linux: 43. .NET Core/5+ 응용 프로그램의 Ubuntu (Debian) 패키지 준비
12719정성태7/19/202113895오류 유형: 737. SharePoint 설치 시 "0x800710D8 The object identifier does not represent a valid object." 오류 발생
12718정성태7/19/202113903개발 환경 구성: 581. Windows에서 WSL로 파일 복사 시 root 소유권으로 적용되는 문제파일 다운로드1
12717정성태7/18/202114102Windows: 195. robocopy에서 파일의 ADS(Alternate Data Stream) 정보 복사를 제외하는 방법
12716정성태7/17/202115233개발 환경 구성: 580. msbuild의 Exec Task에 robocopy를 사용하는 방법파일 다운로드1
12715정성태7/17/202122431오류 유형: 736. Windows - MySQL zip 파일 버전의 "mysqld --skip-grant-tables" 실행 시 비정상 종료 [1]
12714정성태7/16/202115797오류 유형: 735. VCRUNTIME140.dll, MSVCP140.dll, VCRUNTIME140.dll, VCRUNTIME140_1.dll이 없어 exe 실행이 안 되는 경우
12713정성태7/16/202117192.NET Framework: 1077. C# - 동기 방식이면서 비동기 규약을 따르게 만드는 Task.FromResult파일 다운로드1
12712정성태7/15/202116108개발 환경 구성: 579. Azure - 리눅스 호스팅의 Site Extension 제작 방법
... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...