#5121 [py3] Remove unnecessary calls to dict.keys()
Closed: fixed 6 years ago Opened 8 years ago by cheimes.

The keys() method of dict objects behaves differently under Python 2 and Python 3. In 2.x keys() returns a copy of all keys as list, in 3 it returns a view (iterator without a copy). Modernize converts {{{dict.keys()}}} to {{{list(dict.keys())}}} to get the same behavior. This is inefficient, inelegant and (in most cases) not needed.

In most cases keys() can be removed

for loop

for key in somedict.keys():
    ...

equals:

for key in somedict:
    ...

EXCEPTION: a copy is still required when the for-loop body adds or removes entries from somedict.

contains check

if item in somedict.keys():
    ...

equals

if item in somedict:
    ...

NOTE: with keys(), the code is O(n). without it is O(1).

set, string join, list, sorted list

set(somedict.keys()) == set(somedict)



''.join(somedict.keys()) == ''.join(somedict)



keys = somedict.keys()

equals:

keys = list(somedict)



keys = somedict.keys()
keys = keys.sort()

equals:

keys = sorted(somedict)

reverse lookup

The current reverse lookup code relies upon the fact that values() and keys() return the items in the same order. The assumption may not hold forever. Code like

dict(zip(attrs_id2name.values(), attrs_id2name.keys()))

should be written as:

{v: k for k, v in attrs_id2name.iteritems()}

mass moving python3 tickets to FreeIPA 4.6 which should be smaller release targeted mainly on python3 porting.

Metadata Update from @cheimes:
- Issue assigned to mbasti
- Issue set to the milestone: FreeIPA 4.6

7 years ago

Metadata Update from @mbasti:
- Issue close_status updated to: None
- Issue tagged with: py3

6 years ago

Metadata Update from @mbasti:
- Issue assigned to stlaz (was: mbasti)

6 years ago

Metadata Update from @tkrizek:
- Issue set to the milestone: FreeIPA 4.6.1 (was: FreeIPA 4.6)

6 years ago

Fixed in master with
- 353d493 pylint: Iterate through dictionaries

Will be backported as a part of https://pagure.io/freeipa/issue/6874, closing ticket.

Metadata Update from @stlaz:
- Issue close_status updated to: fixed

6 years ago

Login to comment on this ticket.

Metadata