How do I check if a python function changed (in live code)?

前端 未结 2 1063
萌比男神i
萌比男神i 2021-02-04 04:27

If I have a reference to a function I can check it\'s code object f.__code__, get a signature, then perform later checks against this signature to see if the code c

2条回答
  •  执笔经年
    2021-02-04 04:53

    You may to compare bytecode attributes on code object using method.__code__.co_code. For example lets define two classes:

    >>> class A:
    ...     a = 1
    ...     def b(self, b):
    ...             print(self.a + b)
    ... 
    >>> class B:
    ...     a = 1
    ...     def b(self, b):
    ...             print(self.a + b)
    ... 
    >>> A().b.__code__.co_code
    '|\x00\x00j\x00\x00|\x01\x00\x17GHd\x00\x00S'
    >>> B().b.__code__.co_code
    '|\x00\x00j\x00\x00|\x01\x00\x17GHd\x00\x00S'
    >>> A().b.__code__.co_code == B().b.__code__.co_code
    True
    

    and if method b in class A is changed:

    >>> class A:
    ...     a = 1
    ...     def b(self, b):
    ...             print(b + self.a)
    ... 
    >>> A().b.__code__.co_code
    '|\x01\x00|\x00\x00j\x00\x00\x17GHd\x00\x00S'
    >>> A().b.__code__.co_code == B().b.__code__.co_code
    False
    

    or use inspect method inspect.getsource(object) that:

    Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string.

    And if you want to know whether the code has changed in dynamic you may need to reload your class with importlib and compare bytecode.

提交回复
热议问题