Skip to content

__del__ method is not called #985

Open

Description

@jameslan

Steps to Reproduce

If we have a class with __del__ method:

import sys


class Foo:
    def __init__(self, name):
        self.name = name

    def __del__(self):
        sys.stdout.write(self.name + '\n')

Running the following statements with CPython,

def func():
    foo = Foo('Foo 1')
    bar = Foo('Foo 2')
    del bar

func()
foo = Foo('Foo 3')
foo = Foo('Foo 4')

[Expected behavior:]
will get output

Foo 2
Foo 1
Foo 3
Foo 4

[Actual behavior:]
But running with IronPython, there's nothing output.

This blocks #938. FileIO, TextIOWrapper etc classes have finalizer (defined in their base class _IOBase) calling close(). But the finalizer is never called.

Activity

  1. jameslan commented on Oct 15, 2020

    @jameslan
    ContributorAuthor

    __del__ is called by dotnet finalizer. When the IronPython process ends and there's some objects in the finalizer queue, these finalizers won't be invoked.

    So adding the following C# code at the end of PythonContext.Shutdown(),

    GC.Collect();
    GC.WaitForPendingFinalizers();

    we could get partial output

    Foo 3
    Foo 2
    Foo 1
    

    The missing of Foo 4 from the output, means that the global variable is still referenced

  2. BCSharp commented on Oct 15, 2020

    @BCSharp
    Member

    I have run into a similar issue when developing the buffer protocol support for memoryview. Unfortunately, it seems that running gc.collect() is the only way to make it work, due to a different operational principle between the .NET and CPython garbage collectors.

    Perhaps we could always do collect and wait for pending finalizers when the IronPython process closes. It is less clear what to do in embedded scenarios.

  3. slozier commented on Oct 15, 2020

    @slozier
    Contributor

    Interestingly with .NET Framework I get all 4 outputs but with .NET Core only 3 (assuming I add GC collect to PythonContext.Shutdown)?

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions