prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.1k stars 717 forks source link

[Memory leak] There is a slight memory increase after creating and destroying a PromptSession. #1835

Closed vicalloy closed 6 months ago

vicalloy commented 6 months ago

I use PromptSession with prompt_toolkit.contrib.telnet and have noticed a slight memory increase after connecting and disconnecting a session. Below is the code I used to test for memory leaks.

#!/usr/bin/env python3
import sys
import asyncio
import gc
from prompt_toolkit import PromptSession
from pympler import tracker

async def create_session():
    try:
        session = PromptSession()
        # await session.prompt_async()
    except KeyboardInterrupt:
        print("pass")
    del session
    gc.collect()

async def m():
    for _ in range(5):
        tr = tracker.SummaryTracker()
        await create_session()
        tr.print_diff()

asyncio.run(m())

Output:

                                  types |   # objects |   total size
======================================= | =========== | ============
                                   dict |         139 |     12.95 KB
                                   list |          34 |      2.93 KB
   prompt_toolkit.filters.base._AndList |          34 |      1.59 KB
                                   code |           1 |    545     B
  prompt_toolkit.filters.base.Condition |           6 |    288     B
               function (is_returnable) |           2 |    288     B
     prompt_toolkit.filters.base.Always |           4 |    192     B
      function (digraph_symbol_1_given) |           1 |    144     B
                  function (store_info) |           1 |    144     B
                    function (<lambda>) |           1 |    144     B
      function (has_text_before_cursor) |           1 |    144     B
      function (search_buffer_is_empty) |           1 |    144     B
    prompt_toolkit.filters.base._Invert |           2 |     96     B
                                    str |           1 |     87     B
                                   cell |           2 |     80     B