I am using an object that expects a keyword argument for every call, but I never intend to change it. In this case a timeout of 10. What is the best way to add a partialmethods for each attributes.
In my example I want to set a timeout for my session requests http methods.
I could monkeypatch Session.request with a partialmethod. This works fairly well because all of the session methods go through request. Session().post
is actually going through Session.request('post', <inputs>)
.
from requests import Session
Session.request = partialmethod(Session.request, timeout=10)
However, what about use cases where there isn't a single method I can fix or I simply don't want to do something potentially dangerous like monkeypatching.
I have a session helper object that configures the auth and the adapter (omitted here) for the client, but I want different default timeouts for different methods. I can't even monkeypatch the method in that case.
I could do it after standard definition of the class in a loop.
from functools import partialmethod
from requests import Session
class SeshTester:
def __init__(self):
self.s = Session()
def request(self, method, *args, **kwargs):
return self.s.request(method, *args, **kwargs)
for r_method in ['delete', 'get', 'head', 'options']:
setattr(SeshTester, r_method, partialmethod(SeshTester.request, r_method, timeout=7))
for r_method in ['connect', 'put', 'push']:
setattr(SeshTester, r_method, partialmethod(SeshTester.request, r_method, timeout=13))
# this call is equivalent to self.s.request('get', 'http://google.com', timeout=7
print(SeshTester().get('http://google.com'))
I don't think this is very legible, but am unaware how to do this inside of standard class definition. SeshTester object obviously isn't reference-able before it is made, but I don't want to repeat myself by doing post = partialmethod(request, 'post', timeout=13)
for every possible http method.
I would like to perform this loop in the class, but don't know how to reference the object before it's fully defined.
SeshTester
(and maybe name that better?) for testing purposes. \$\endgroup\$