Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reusing Context Manager for Different Functions in Procedural Script #109

Open
cjcjcj opened this issue Nov 1, 2024 · 0 comments
Open

Comments

@cjcjcj
Copy link

cjcjcj commented Nov 1, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant