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

generate_async type annotation does not support .aclose() #1955

Open
graingert opened this issue Apr 7, 2024 · 0 comments · May be fixed by #1957 or #1960
Open

generate_async type annotation does not support .aclose() #1955

graingert opened this issue Apr 7, 2024 · 0 comments · May be fixed by #1957 or #1960

Comments

@graingert
Copy link

graingert commented Apr 7, 2024

given:

import contextlib
import sys
import trio
from collections.abc import AsyncGenerator

from jinja2 import Template, select_autoescape


class MyModel:
    class objects:
        @staticmethod
        async def all() -> AsyncGenerator[str, None]:
            while True:
                yield "hello"


template = """
<html>
  <head></head>
  <body>
    {% for m in model.objects.all() %}
        {{ m }}
        {% break %}
    {% endfor %}
  </body>
</html>
"""


async def amain() -> None:
    agen = Template(
        source=template, enable_async=True, extensions=["jinja2.ext.loopcontrols"]
    ).generate_async(model=MyModel)
    async for v in agen:
        print(v)
        break


def main() -> int | None:
    return trio.run(amain)


if __name__ == "__main__":
    sys.exit(main())

it outputs:

python -Wall demo_jinja_asyncgens.py 

<html>
  <head></head>
  <body>
    
/home/graingert/.virtualenvs/demo-jinja-asyncgens/lib/python3.12/site-packages/trio/_core/_run.py:2599: ResourceWarning: Async generator 'jinja2.environment.Template.generate_async' was garbage collected before it had been exhausted. Surround its use in 'async with aclosing(...):' to ensure that it gets cleaned up as soon as you're done using it.
  msg = task.context.run(next_send_fn, next_send)
ResourceWarning: Enable tracemalloc to get the object allocation traceback
/home/graingert/.virtualenvs/demo-jinja-asyncgens/lib/python3.12/site-packages/jinja2/environment.py:1371: ResourceWarning: Async generator '<<template>>.root' was garbage collected before it had been exhausted. Surround its use in 'async with aclosing(...):' to ensure that it gets cleaned up as soon as you're done using it.
  yield event
ResourceWarning: Enable tracemalloc to get the object allocation traceback

following the instructions in mypy results in:

demo_jinja_asyncgens.py:31: error: Value of type variable "_SupportsAcloseT" of "aclosing" cannot be "AsyncIterator[str]" [type-var]

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