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

Simulate __exit__ using Drop trait #2949

Closed
AsafFisher opened this issue Feb 13, 2023 · 4 comments
Closed

Simulate __exit__ using Drop trait #2949

AsafFisher opened this issue Feb 13, 2023 · 4 comments

Comments

@AsafFisher
Copy link

If one want to use a with statment with a pyclass then __exit__ can be automatically implemented by calling drop on the pyclass.
This elimnates the need to implement a __exit__ function.

#[pyclass]
struct DebugController {
    conn: TcpStream,
}
impl Drop for DebugController{
    fn drop(&mut self){
        // Do RAII stuff idk send bye bye message using the socket
    }
}
with DebugController as d:
        d.do_stuff()

I am thinking about it and not sure if it's a good idea... because implementing __exit__ might seem easier.

@birkenfeld
Copy link
Member

Hey Asaf, can you elaborate a bit? I'm not sure what you're proposing here.

@AsafFisher
Copy link
Author

Ultimately if a struct impl Drop then __exit__ can be automatically implemented to call the drop function

@birkenfeld
Copy link
Member

AFAICS that wouldn't be possible, since there's no guarantee in Python that the context manager object is destroyed at that point.

And if the Python object is still alive, the underlying Rust object must stay alive as well, so it can't be dropped.

@davidhewitt
Copy link
Member

Agree with @birkenfeld

To give some additional detail here, in general we don't automatically implement any Python methods based on the existence of a Rust trait. I think to do that would probably require specialization.

Also, some other discussion about Drop and __exit__ can be found at #1205 (comment)

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

No branches or pull requests

3 participants