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

del should call __del__ method #1802

Closed
blazewicz opened this issue Jan 28, 2016 · 4 comments
Closed

del should call __del__ method #1802

blazewicz opened this issue Jan 28, 2016 · 4 comments

Comments

@blazewicz
Copy link
Contributor

Example test with custom object:

class Foo():
    def __del__(self):
        print('__del__')

f = Foo()
del f  # should print '__del__'

Also for builtin types with finaliser, like socket.socket.
Example case:

s = socket.socket()
s.connect(addr)  # binds "hard" socket to object `s`
...
del s  # s.close() has not been called - "hard" socket will never be released
@dpgeorge
Copy link
Member

This is not strictly a bug. CPython docs say "del x doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero." See https://docs.python.org/3/reference/datamodel.html#object.__del__

Workaround would be to call gc.collect() after doing the del. Then it should collect the object and call the finaliser.

Additional workaround for socket would be to call s.close() instead of doing del s.

Did you hit a problem with this in real code?

@stinos
Copy link
Contributor

stinos commented Jan 28, 2016

The 'real python' way would imo be context managers, i.e. __enter__ and __exit__ methods. If you add them to your Foo class you'd have a nice situation like

with Foo() as f:  # calls __enter__
  pass
# __exit__ called when f goes out of scope

# ... some time later ....
import gc
gc.collect()  # f is out of scope so it's finaliser will be called

@peterhinch
Copy link
Contributor

My understanding is that good coding practice is to assume that __del__() may never be called at all.

@dpgeorge
Copy link
Member

dpgeorge commented Mar 7, 2016

Closed in favour of #1878.

@dpgeorge dpgeorge closed this as completed Mar 7, 2016
nickzoic pushed a commit to nickzoic/micropython that referenced this issue Apr 16, 2019
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

4 participants