ul-gh / PiPyADC

Python classes for interfacing Texas Instruments analog-to-digital converters with the Raspberry Pi
GNU Lesser General Public License v2.1
69 stars 27 forks source link

fix closing self.open_spi_handles #32

Open lff5 opened 1 year ago

lff5 commented 1 year ago

self.open_spi_handles looks like this: {7: 7}

calling reversed(self.open_spi_handles) throws:

Traceback (most recent call last): File "", line 1, in TypeError: 'dict' object is not reversible

ul-gh commented 1 year ago

Hi,

thank you for looking into this!

You seem to be using a Python version before 3.6.

Since Python 3.6, Dictionaries are ordered by default and they also have a .__reversed__() method, which means you can run the built-in function reversed() on the dictionary itself:

Python 3.10.7 (main, Nov  2 2022, 18:49:29) [GCC 12.2.0]
In [1]: d = {"a": 4, "b": 5, "c": 6}

In [2]: d.__reversed__()
Out[2]: <dict_reversekeyiterator at 0x7f230e4e5530>

In [3]: list(reversed(d))
Out[3]: ['c', 'b', 'a']

In [4]: dict(reversed(d.items()))
Out[4]: {'c': 6, 'b': 5, 'a': 4}

https://docs.python.org/3/library/functions.html#reversed https://softwaremaniacs.org/blog/2020/02/05/dicts-ordered/

I admit that for backwards-compatibility, your fix might still be helpful. Can you please check that you can use the compatibility fix without the list() constructor like in the comment: https://github.com/ul-gh/PiPyADC/pull/32#discussion_r1031885978_

Please let me know if that works for you.

lff5 commented 1 year ago

Hi,

Running on Raspberry Pi 3 with old Raspbian GNU/Linux 10 (buster). Python 3.7.3 (default, Jul 25 2020, 13:03:44)

strangely there is no reversed() function in dict object despite being > 3.7 version. I tested, reversed(self.open_spi_handles.keys()) it also throws.

Python 3.7.3 (default, Jul 25 2020, 13:03:44) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> reversed({"a": 1, "b": 2})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not reversible

>>> reversed({"a": 1, "b": 2}.keys())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict_keys' object is not reversible

>>> reversed(list({"a": 1, "b": 2}.keys()))
<list_reverseiterator object at 0x7669cb90>
>>> 

I think i will just update the machine. Up to you if you want to make it backwards compatible.