Re: iterating over DictRow

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: Karsten Hilbert <Karsten(dot)Hilbert(at)gmx(dot)net>, psycopg(at)lists(dot)postgresql(dot)org
Subject: Re: iterating over DictRow
Date: 2020-09-25 22:19:12
Message-ID: 65a4f678-4c7f-d88b-3709-e0686a561461@aklaver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: psycopg

On 9/25/20 2:16 PM, Karsten Hilbert wrote:
> On Fri, Sep 25, 2020 at 09:06:43AM -0700, Adrian Klaver wrote:
>
>>> 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.
>>
>> Well you can do, borrowing from previous example:
>>
>> for ky in r0._index:
>> print(ky)
>>
>> for ky in r0._index:
>> print(r0[ky])
>>
>> Where _index is a substitute for *.keys().
>
> Sure, there's a number of solutions to my immediate problem,
> the fitting of which is
>
> for key in dict(DictRow):
>
> That's the best fit because my
>
> def _escape_dict(the_dict, ...):
>
> was inaptly named. It should have been (and now is)
>
> def _escape_dict_like(dict_like, ...):
>
> within which
>
> dict(dict_like)
>
> is quite the thing to do despite having to make something a
> duck which already nearly quacks like one is somehwat
> unfortunate.

I'm pretty sure DictRow has had the same behavior for some time so:

Are you migrating from Python 2?

Or what changed that made this show up?

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

--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com

In response to

Responses

Browse psycopg by date

  From Date Subject
Next Message Karsten Hilbert 2020-09-25 22:25:23 Re: iterating over DictRow
Previous Message Karsten Hilbert 2020-09-25 21:16:35 Re: iterating over DictRow