provinzkraut / unasyncd

Transforming asynchronous to synchronous Python code
MIT License
18 stars 3 forks source link

Question: Import for type annotations / type checking #16

Open afuetterer opened 1 week ago

afuetterer commented 1 week ago

Hi there, this is related to #15.

I ran into another issue, when using the project.

Let's say I have the same set up: I want to translate the async client to a client, as well as the unit tests.

Let's say I have a fixture for both clients in conftest.py, and use the clients in test functions.

A minimal example:

# conftest.py
import pytest

from src import AsyncClient, Client

@pytest.fixture(scope="session")
def client() -> Client:
    return Client()

@pytest.fixture(scope="session")
def async_client() -> AsyncClient:
    return AsyncClient()
# test_async.py
from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from src import AsyncClient

async def test_async_client(async_client: AsyncClient):
    response = await async_client.get()
    assert response

When I run unasynd I get

# test_sync.py
from __future__ import annotations
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from src import AsyncClient # <- this is not translated

def test_async_client(client: Client):
    response = client.get()
    assert response

I have this add_replacements config

# pyproject.toml
[tool.unasyncd.add_replacements]
"AsyncClient" = "Client"
"async_client" = "client"

The import in the if TYPE_CHECKING block is not recognized, I guess?

provinzkraut commented 1 week ago

Hm. This should work, and there's actually a test for this: https://github.com/provinzkraut/unasyncd/blob/58b80b7fe9c17d42155e015794e3dbcff0ce8b40/test/test_tree_transformer.py#L984

Can you try with the fully qualified name for the replacements?

afuetterer commented 1 week ago

Thanks, will do.

afuetterer commented 1 week ago

Okay, thanks. Using the fully qualified name solved the issue.

provinzkraut commented 1 week ago

Reopening this because I think it's still a bug and should work with the simple replacement as well. I'll check it out when I have the time

afuetterer commented 1 week ago

Alright, sure thing.