Skip to content

Usage of weakref.finalize causes RuntimeError: Loop is not running #495

@provinzkraut

Description

@provinzkraut
import pytest
from adlfs import AzureBlobFileSystem


@pytest.fixture()
def fs():
    return AzureBlobFileSystem(..., asynchronous=True)


@pytest.mark.asyncio
async def test_something(fs: AzureBlobFileSystem):
    pass

A simple setup like this, where the fs is created within an async context (event loop will be set up by pytest-asyncio here), will result in a RuntimeError: Loop is not running during gc.

This is caused by these lines:

adlfs/adlfs/spec.py

Lines 346 to 349 in adb9c53

weakref.finalize(self, sync, self.loop, close_service_client, self)
if self.credential is not None:
weakref.finalize(self, sync, self.loop, close_credential, self)

which obtain a reference to the current event loop, however, since there's no guarantee when finalization on the refs will run, this can also happen after the referenced event loop has been closed.


Since all they're doing is closing things, I would like to propose adding a close method to the implementation, which can be manually invoked to do proper cleanup, and a conditional check on the finalizers, so they may not run if the resources have already been closed.

Then, all that's needed in the code to fix the issue is something like

@pytest.fixture()
async def fs():
    fs = AzureBlobFileSystem(..., asynchronous=True)
    yield fs
    await fs.close()

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