OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Python hooks methods at runtime

  • Thread starter Thread starter xinlin hou
  • Start date Start date
X

xinlin hou

Guest
Is there a way for Python to hook specified methods at runtime, similar to Java's bytebuddy framework, to modify bytecode at runtime,

For example, there is the following code

Code:
def method(str):
    print(str)
    
def new_method(originMethod):
    print("new_method")
    originMethod.method()
    
if __name__ == '__main__':
    
    set_hook(method,new_method)
    
    method("a")

I want his final output to be as follows

Code:
new_method
a

I don't want to use decorators because they cannot be modified at runtime
<p>Is there a way for Python to hook specified methods at runtime, similar to Java's bytebuddy framework, to modify bytecode at runtime,</p>
<p>For example, there is the following code</p>
<pre><code>def method(str):
print(str)

def new_method(originMethod):
print("new_method")
originMethod.method()

if __name__ == '__main__':

set_hook(method,new_method)

method("a")
</code></pre>
<p>I want his final output to be as follows</p>
<pre><code>new_method
a
</code></pre>
<p>I don't want to use decorators because they cannot be modified at runtime</p>
 

Online statistics

Members online
0
Guests online
3
Total visitors
3
Top