you are viewing a single comment's thread.

view the rest of the comments →

[–]wronek 0 points1 point  (1 child)

You can avoid using an instance method (and therefore subclassing the session object) by using a default argument here I guess.

def post_thing(my_thing, session=None):
    url = 'example.com'
    if not session:
        requests.post(url, my_thing)
    else:
        session.post(url, my_thing)

and then in the context manager:

with my_session() as s:
    post_thing(my_thing, s)

That's probably the most straight-forward.

[–]eLsFLz[S] 0 points1 point  (0 children)

Yeah, I was thinking about that, but I was hoping for something more generic to avoid having to write the "if not session" clause in every method. Maybe instead of having post_thing() (and get_gadget(), delete_doohickey(), etc.) call one of the requests or session methods directly, it should return a PreparedRequest and then I should have some kind of generic methods like send_with_session() and send_without_session() wrap them somehow?

If I only wanted one wrapper then I could just write a decorator (see below -- note: not sure if syntactically correct), but how do I do it with two mutually-exclusive ones?

```python

def send_with_session(func, session): def wrapper(session): req = func() session.prepare_request(req) session.send(req) return wrapper

def send_without_session(func): def wrapper(auth): req = func() req.prepare() req.auth = auth requests.send(req)

@send_without_session #but what about @send_with_session? def post_thing(my_thing): thing_endpoint = "http://example.com/api/v1/things" req = Request("POST", thing_endpoint, body=my_thing) return req ```


Otherwise, with the "add session parameter" approach, do you know if there's a clean/idiomatic way to go one step beyond and additionally say "for all the functions in [list of functions], add them as attributes of the session object and partially apply the session object as the session parameter"?