3

I have a package in my virtual environment installed in the site-packages folder of it. In that package there is a module with a bunch of functions. I want to change one of these functions without touching the package code, so I want to make a hook of that module and then change/overwrite the function so it behaves in the way I want.

I don't know if this is even possible in Python (I'm new to the language).

Example:

I have a package called their_package in my site-packages folder, inside I have a module named whatever.py with the following code:

import sys
import os
def this_is_a_function(parameter):
 //whatever logic in here
 return result

What I want is to hook the whatever.py module so I can redefine the this_is_a_function to have a different logic. Is this possible? I would appreciate a lot a code sample!

tripleee
192k37 gold badges319 silver badges370 bronze badges
asked Apr 8, 2014 at 9:43
2
  • How do you plan to use that hooked module later? Do you want to hook it only for one scenario (piece of logic), or for the whole Python interpreter session? Commented Apr 8, 2014 at 9:55
  • Yes, there is a lbrary called wphooks for this purpose Commented Dec 12, 2025 at 8:16

1 Answer 1

5

You can redefine your function with:

import whatever
def this_is_a_function(parameter):
 pass
whatever.this_is_a_function = this_is_a_function
answered Apr 8, 2014 at 9:47
Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand where is "redefined the this_is_a_function to have a different logic" as asked by the OP.
@DenisBitouzé It runs pass instead of whatever the function did before. Obviously replace this with something more complex if that's what you want.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.