Skip to content

Reusing Context Manager for Different Functions in Procedural Script #109

@cjcjcj

Description

@cjcjcj

I have a script written in a procedural style, and I want to reuse a context manager for different functions without recreating it. Specifically, I want to manage the lifecycle of MyClient (a subclass of httpx.Client) using a context manager.

Here's an example of my current setup:

class MyClient(httpx.Client): ...

@inject.autoparams
def fetch_service(service: str, *, client: MyClient):
   ...
   client.get()
   ...

@inject.autoparams
def fetch_service_info(service_id: int, *, client: MyClient):
  ...
  client.get()
  ...

def main(services: list[str]):
   for service in services:
       service_id = fetch_service(service)
       fetch_service_info(service_id)

def config(binder: inject.Binder):
    binder.bind_to_constructor(MyClient, make_my_client_client)

def make_my_client_client():
    return httpx.Client(
        base_url=...,
        verify=False,
        follow_redirects=True,
        timeout=10.0,
    )

inject.configure(config, once=True)

I want to be able to close MyClient using a context manager. How can I achieve this?

I've tried to keep it short, please let me know if I need to provide more details.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions