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

Implement __aenter__ and __aexit__ in Client class for use with context manager #121

Closed
cwrneiro opened this issue Sep 25, 2022 · 4 comments

Comments

@cwrneiro
Copy link

This simple workaround is already enough to work with asynchronous context managers:

class Client(coc.Client):
	async def __aenter__(self):
		self.__init__()
		return self

	async def __aexit__(self, *args):
		await self.http.close()

It can be easily implemented into the official code for easier use of the Client class, without the need to close after using it (also making it more organized):

async def main():
	async with coc.Client() as client:
		# do stuff...

if __name__ == "__main__":
	asyncio.run(main())

versus:

async def main():
	client =  coc.Client():
	# do stuff...
	client.close()

if __name__ == "__main__":
	asyncio.run(main())
@majordoobie
Copy link
Collaborator

Great work! This was something that the creator wanted to add. Did you run all the examples with this update?

@cwrneiro
Copy link
Author

Thanks! I've only tried with basic scripts, but it should work with almost anything as it uses the class own init() and http.close() methods

@cwrneiro cwrneiro reopened this Sep 27, 2022
@doluk
Copy link
Collaborator

doluk commented Sep 27, 2022

If you create a pr, we can test and merge it!

@majordoobie
Copy link
Collaborator

Thank you for the suggestion. Context manager is now available in v2.2.0

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

3 participants