Re: iterating over DictRow

Поиск
Список
Период
Сортировка
От Karsten Hilbert
Тема Re: iterating over DictRow
Дата
Msg-id 20200925074820.GC2138@hermes.hilbert.loc
обсуждение исходный текст
Ответ на Re: iterating over DictRow  (Adrian Klaver <adrian.klaver@aklaver.com>)
Ответы Re: iterating over DictRow  (Adrian Klaver <adrian.klaver@aklaver.com>)
Список psycopg
Adrian,

thanks for tracing my misunderstanding. I should have
confirmed my suspicion here:

> https://github.com/psycopg/psycopg2/blob/fbba461052ae6ebc43167ab69ad91cadb7914c83/lib/extras.py

> class DictRow(list):

>     def __getitem__(self, x):
>             if not isinstance(x, (int, slice)):
>                     x = self._index[x]
>             return super(DictRow, self).__getitem__(x)
>
> So if the value passed to __getitem__() is a integer or slice it does a list
> index.

Indeed. I wonder whether that should be mentioned in the
psycopg2 docs somewhere as it might be considered to violate
the Principle Of Least Astonishment.

Or rather, this issues seems unfortunate fallout from python3:

In py2 one *had* to do DictRow.keys() to iterate over the
keys. In py3

    for key in DictRow:

is the suggested idiom for that which, however, iterates over
DictRow as a list (as it always did).

DictRow.keys() still exists on dicts in py3 (and is not
deprec(i?)ated to my knowledge) but now returns a memoryview
(dict_keys, that is) rather than a list, which brings with it
its own set of issues (dict and keys "list" are not
independant objects anymore).

So, neither using py2's

    for key in DictRow.keys():

under py3 nor changing to py3's

    for key in DictRow:            # beep: variable wrongly named

leads to fully equivalent code. So this is a py2/py3 Gotcha
in psycopg2.

Not that I complain, but worth a mention in the DictRow docs
somewhere ?

Karsten
--
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B



В списке psycopg по дате отправления:

Предыдущее
От: Adrian Klaver
Дата:
Сообщение: Re: iterating over DictRow
Следующее
От: Adrian Klaver
Дата:
Сообщение: Re: iterating over DictRow