I have about 20 methods to redirect to a wrapper method that takes the original method, and the rest of the arguments:
class my_socket(parent):
def _in(self, method, *args, **kwargs):
# do funky stuff
def recv(self, *args, **kwargs):
return self._in(super().recv, *args, **kwargs)
def recv_into(self, *args, **kwargs):
return self._in(super().recv_into, *args, **kwargs)
# and so on...
How can I add more of these methods programmatically? This is about as far as I get before everything starts to look wrong:
for method in 'recv', 'recvfrom', 'recvfrom_into', 'recv_into', ...:
setattr(my_socket, method, ???)
Can I do this by assigning within the class definition, or something else that feels more natural?
class my_socket(parent):
def makes_recv_methods(name):
# wraps call to name
def recv_meh = makes_recv_methods('recv_meh')
I'd prefer to use __get__
and friends when possible over magic functions from types
.
I'd like to expand on the accepted answer. I wanted to potentially have a very long list of decorator methods applied to a very long list of methods.
And here is the class that wraps the original
I'd do it by running some code to generate the methods from a list after the class is defined - you could put this into a decorator.
wilberforce proposal works, but there is a simpler way using OOP only:
You could use cog.
This has the added advantages of easily being updated, not touching your code outside of the end comment, and you can twiddle the generated code if necessary.
I've successfully used cog for generating boilerplate on another project, mixed in with the non generated code. It started out reading an input file of instructions into a dictionary. Then for each section of boilerplate it used that piece of the dictionary to know what to write.
I edit the instruction file in one spot, instead of twenty different places in the boilerplate.