I am using a class A from an open-source library.
I want to add a function fn to A without changing the source of the library, so let's say the function fn is available only in my project.
Is it possible? If so, how could I do that?
Thanks
Problem
# a.py module
def print_message(msg):
print(msg)
# b.py module
from a import print_message
def execute():
print_message("Hello")
# c.py module which will be executed
import b
b.execute()
Answer
import a
def _new_print_message(message):
print("NEW: " + message)
a.print_message = _new_print_message
import b
b.execute()
You have to first import a, then override the function and then import b so that it would use the a module that is already imported (and changed).
Add a function to A: can you please clarify with a small example? E.g. do you want to add a method, a class method, or something else? What have you tried?