I am using a library that takes some keyword arguments during the initialization of the object. These keyword arguments define the callback objects/functions that are called when a specific event occurs. The callback objects themselves need to reference the object that called them and have some additional data that comes from the class/object instance itself.
What I would like to do is pass a reference to another object into one of these call backs when initializing in order to avoid using a global variable.
How/where would I pass the reference to the object? Do I need to subclass? If I do need to subclass can I accomplish this without understanding the working behind the class/library? I tried looking at the source to try and figure something out but unfortunately it's a bit past my understanding.
Example which will hopefully get my point across:
def One(eI):
*...do some stuff...*
def Two(eI, data, ref_I_want_to_add):
*do some other stuff*
ref_I_want_to_pass = anotherClass(diff_arg,diff_arg2):
*...you know the deal...*
eI = exampleClass(argOne=One, ..., argN=N)
The first thing that comes to mind is to use something like
eI = exampleClass(argOne=One, argTwo=Two(ref_I_want_to_pass), ..., argN)
But that obviously doesnt work because I get a TypeError: argTwo takes 0 positional arguments but 1 was given
More precisely I am using the websocket client library and in order to create a WebSocketApp
object which handles the connection you instaniate the object with something like
ws = websocket.WebSocketApp(uri, on_open=on_open, on_message=on_message, on_ping=on_ping)
now I have a function named on_message
that handles the incoming messages and I told the ws
object during instantiation of WebSocketApp
that I would like to use that function to handle the incoming messages or rather what to do with them.
I would like to update another object when a new message comes in, now I can of course use a global variable for that but it doesn't seem like the right way to do it and it would be nice if I could pass a reference to that object when initializing a WebSocketApp
object, with something like:
ws = websock.WebSocketApp(uri, on_message=on_message(ref_to_Obj), on_open=on_open, on_ping=on_ping)
But obviously that doesnt work because again I get a TypeError: argTwo takes 0 positional arguments but 1 was given
error.
I'm not entirely sure how to do this. Subclassing comes to mind but even then I'm kind of lost, I will admit that subclassing is a topic I need more work on, I get the idea behind it and can do all the basic examples they use in tutorials but more complex classes can stump me.
If you want a local variable to be passed onto a function, you need to create a closure around that variable. We can do that with lambda
.
eI = exampleClass(argOne=One, ..., argN=lambda x, y: N(x, y, ref_I_want_to_pass))