devbis / ble2mqtt

Bluetooth to MQTT bridge, add your bluetooth-capable (including controllable) devices to your smart home
MIT License
137 stars 26 forks source link

compat: cache Bleak version #89

Closed QuintinHill closed 4 months ago

QuintinHill commented 4 months ago

The get_bleak_version call leads to opening a file to get the version. This is fairly redundant as the Bleak version will be stable for the lifetime of the process. Moreover it seems to trigger a small memory leak according to tracemalloc:

/usr/lib64/python3.12/pathlib.py:1013: size=708 B (+59 B), count=12 (+1), average=59 B /usr/lib64/python3.12/pathlib.py:1013: size=767 B (+59 B), count=13 (+1), average=59 B

So cache the value of the function to avoid a file access and a memory leak.

Stacktrace of call to pathlib ``` File "/usr/lib64/python3.12/asyncio/events.py", line 88 self._context.run(self._callback, *self._args) File "/lib64/python3.12/site-packages/ble2mqtt/ble2mqtt.py", line 208 scanner = get_scanner( File "/lib64/python3.12/site-packages/ble2mqtt/compat.py", line 24 bleak_version = get_bleak_version() File "/lib64/python3.12/site-packages/ble2mqtt/compat.py", line 20 return metadata.version('bleak') File "/usr/lib64/python3.12/importlib/metadata/__init__.py", line 889 return distribution(distribution_name).version File "/usr/lib64/python3.12/importlib/metadata/__init__.py", line 467 return self.metadata['Version'] File "/usr/lib64/python3.12/importlib/metadata/__init__.py", line 444 self.read_text('METADATA') File "/usr/lib64/python3.12/importlib/metadata/__init__.py", line 819 return self._path.joinpath(filename).read_text(encoding='utf-8') File "/usr/lib64/python3.12/pathlib.py", line 1027 with self.open(mode='r', encoding=encoding, errors=errors) as f: File "/usr/lib64/python3.12/pathlib.py", line 1013 return io.open(self, mode, buffering, encoding, errors, newline) ```
devbis commented 4 months ago

Thanks!