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

Implementing __enter__/__exit__ on Client like SimpleClient #1274

Closed
jamesbraza opened this issue Nov 8, 2023 · 2 comments
Closed

Implementing __enter__/__exit__ on Client like SimpleClient #1274

jamesbraza opened this issue Nov 8, 2023 · 2 comments

Comments

@jamesbraza
Copy link

Is your feature request related to a problem? Please describe.

It looks like as of 5.10.0, SimpleClient supports __enter__/__exit__ for calling disconnect. This is nice for Pythonic code and ensuring disconnect gets called even upon Exception.

Describe the solution you'd like

Can we port this same capability to Client?

Describe alternatives you've considered

One can use a DIY contextlib.contextmanager for this:

from contextlib import contextmanager

import socketio


@contextmanager
def connection(
    client: socketio.Client, *connect_args, **connect_kwargs
) -> Iterator[socketio.Client]:
    client.connect(*connect_args, **connect_kwargs)
    try:
        yield client
    finally:
        client.disconnect()

It would be nice if the source code for Client directly supported __enter__/__exit__ though to avoid this extra code.

Logs

N/a

Additional context
Add any other context or screenshots about the feature request here.

@miguelgrinberg
Copy link
Owner

miguelgrinberg commented Nov 8, 2023

I don't believe this is very useful on the event-based client, because it is event based, so the decision to disconnect is unlikely to be made in the main function. Normally the disconnection will be triggered inside an event handler, or remotely by the server.

Likewise, your claim that this can disconnect when there is an exception does not really seem very likely, since all the logic is in event handlers. An exception raised in an event handler would happen on a separate thread and would not interrupt the client nor the application.

@jamesbraza
Copy link
Author

Okay, I didn't realize Client was supposed to be event based. I follow what you're saying, thanks for the detailed explanation. I guess not having __enter__ and __exit__ implemented help enforce that usage pattern.

Feel free to close this out

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

2 participants