Skip to content

Commit e3b267e

Browse files
committed
Remove OrderedDict in favor of python3.7+ dict
After we drop support for python3.6 we can relly that dictionaries preserve the insertion order: https://docs.python.org/3.7/whatsnew/3.7.html This means we can replace the usage of OrderedDict with a standard dictionaries. Something we have to keep in mind is that even thought the insertion order is preserved the equality comparison for normal dicts is insensitive for normal dicts compared to OrderedDict For example: >>> OrderedDict([(1,1), (2,2)]) == OrderedDict([(2,2), (1,1)]) False >>> dict([(1,1), (2,2)]) == dict([(2,2), (1,1)]) True Signed-off-by: Martin Vrachev <[email protected]>
1 parent 0f59f4b commit e3b267e

File tree

4 files changed

+27
-36
lines changed

4 files changed

+27
-36
lines changed

examples/repo_example/basic_repo.py

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
"""
2626
import os
2727
import tempfile
28-
from collections import OrderedDict
2928
from datetime import datetime, timedelta
3029
from pathlib import Path
3130
from typing import Any, Dict
@@ -103,7 +102,7 @@ def _in(days: float) -> datetime:
103102
signed=Targets(
104103
version=1, spec_version=SPEC_VERSION, expires=_in(7), targets={}
105104
),
106-
signatures=OrderedDict(),
105+
signatures={},
107106
)
108107

109108
# For the purpose of this example we use the top-level targets role to protect
@@ -134,7 +133,7 @@ def _in(days: float) -> datetime:
134133
expires=_in(7),
135134
meta={"targets.json": MetaFile(version=1)},
136135
),
137-
OrderedDict(),
136+
{},
138137
)
139138

140139
# Timestamp (freshness)
@@ -156,7 +155,7 @@ def _in(days: float) -> datetime:
156155
expires=_in(1),
157156
snapshot_meta=MetaFile(version=1),
158157
),
159-
OrderedDict(),
158+
{},
160159
)
161160

162161
# Root (root of trust)
@@ -195,7 +194,7 @@ def _in(days: float) -> datetime:
195194
},
196195
consistent_snapshot=True,
197196
),
198-
signatures=OrderedDict(),
197+
signatures={},
199198
)
200199

201200
# NOTE: We only need the public part to populate root, so it is possible to use
@@ -292,7 +291,7 @@ def _in(days: float) -> datetime:
292291
expires=_in(7),
293292
targets={target_path: target_file_info},
294293
),
295-
signatures=OrderedDict(),
294+
signatures={},
296295
)
297296

298297

@@ -313,20 +312,15 @@ def _in(days: float) -> datetime:
313312
keys[delegatee_name]
314313
)
315314
},
316-
roles=OrderedDict(
317-
[
318-
(
319-
delegatee_name,
320-
DelegatedRole(
321-
name=delegatee_name,
322-
keyids=[keys[delegatee_name]["keyid"]],
323-
threshold=1,
324-
terminating=True,
325-
paths=["*.py"],
326-
),
327-
)
328-
]
329-
),
315+
roles={
316+
delegatee_name: DelegatedRole(
317+
name=delegatee_name,
318+
keyids=[keys[delegatee_name]["keyid"]],
319+
threshold=1,
320+
terminating=True,
321+
paths=["*.py"],
322+
),
323+
},
330324
)
331325

332326
# Remove target file info from top-level targets (delegatee is now responsible)

examples/repo_example/hashed_bin_delegation.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
import hashlib
2020
import os
2121
import tempfile
22-
from collections import OrderedDict
2322
from datetime import datetime, timedelta
2423
from pathlib import Path
2524
from typing import Any, Dict, Iterator, List, Tuple
@@ -160,10 +159,10 @@ def find_hash_bin(path: str) -> str:
160159
keys["bin-n"]
161160
)
162161
},
163-
roles=OrderedDict(),
162+
roles={},
164163
),
165164
),
166-
signatures=OrderedDict(),
165+
signatures={},
167166
)
168167

169168
# The hash bin generator yields an ordered list of incremental hash bin names
@@ -190,7 +189,7 @@ def find_hash_bin(path: str) -> str:
190189
signed=Targets(
191190
version=1, spec_version=SPEC_VERSION, expires=_in(7), targets={}
192191
),
193-
signatures=OrderedDict(),
192+
signatures={},
194193
)
195194

196195
# Add target file

tests/repository_simulator.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@
4747
import logging
4848
import os
4949
import tempfile
50-
from collections import OrderedDict
5150
from dataclasses import dataclass, field
5251
from datetime import datetime, timedelta
5352
from typing import Dict, Iterator, List, Optional, Tuple
@@ -167,15 +166,15 @@ def _initialize(self) -> None:
167166
"""Setup a minimal valid repository."""
168167

169168
targets = Targets(1, SPEC_VER, self.safe_expiry, {}, None)
170-
self.md_targets = Metadata(targets, OrderedDict())
169+
self.md_targets = Metadata(targets, {})
171170

172171
meta = {"targets.json": MetaFile(targets.version)}
173172
snapshot = Snapshot(1, SPEC_VER, self.safe_expiry, meta)
174-
self.md_snapshot = Metadata(snapshot, OrderedDict())
173+
self.md_snapshot = Metadata(snapshot, {})
175174

176175
snapshot_meta = MetaFile(snapshot.version)
177176
timestamp = Timestamp(1, SPEC_VER, self.safe_expiry, snapshot_meta)
178-
self.md_timestamp = Metadata(timestamp, OrderedDict())
177+
self.md_timestamp = Metadata(timestamp, {})
179178

180179
roles = {role_name: Role([], 1) for role_name in TOP_LEVEL_ROLE_NAMES}
181180
root = Root(1, SPEC_VER, self.safe_expiry, {}, roles, True)
@@ -185,7 +184,7 @@ def _initialize(self) -> None:
185184
root.add_key(role, key)
186185
self.add_signer(role, signer)
187186

188-
self.md_root = Metadata(root, OrderedDict())
187+
self.md_root = Metadata(root, {})
189188
self.publish_root()
190189

191190
def publish_root(self) -> None:
@@ -357,7 +356,7 @@ def add_delegation(
357356

358357
# Create delegation
359358
if delegator.delegations is None:
360-
delegator.delegations = Delegations({}, OrderedDict())
359+
delegator.delegations = Delegations({}, {})
361360
# put delegation last by default
362361
delegator.delegations.roles[role.name] = role
363362

@@ -368,7 +367,7 @@ def add_delegation(
368367

369368
# Add metadata for the role
370369
if role.name not in self.md_delegates:
371-
self.md_delegates[role.name] = Metadata(targets, OrderedDict())
370+
self.md_delegates[role.name] = Metadata(targets, {})
372371

373372
def write(self) -> None:
374373
"""Dump current repository metadata to self.dump_dir

tuf/api/metadata.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@
3232
import io
3333
import logging
3434
import tempfile
35-
from collections import OrderedDict
3635
from datetime import datetime
3736
from typing import (
3837
IO,
@@ -113,7 +112,7 @@ class Metadata(Generic[T]):
113112
signing the canonical serialized representation of 'signed'.
114113
"""
115114

116-
def __init__(self, signed: T, signatures: "OrderedDict[str, Signature]"):
115+
def __init__(self, signed: T, signatures: Dict[str, Signature]):
117116
self.signed: T = signed
118117
self.signatures = signatures
119118

@@ -150,7 +149,7 @@ def from_dict(cls, metadata: Dict[str, Any]) -> "Metadata[T]":
150149
raise ValueError(f'unrecognized metadata type "{_type}"')
151150

152151
# Make sure signatures are unique
153-
signatures: "OrderedDict[str, Signature]" = OrderedDict()
152+
signatures: Dict[str, Signature] = {}
154153
for sig_dict in metadata.pop("signatures"):
155154
sig = Signature.from_dict(sig_dict)
156155
if sig.keyid in signatures:
@@ -1211,7 +1210,7 @@ class Delegations:
12111210
def __init__(
12121211
self,
12131212
keys: Dict[str, Key],
1214-
roles: "OrderedDict[str, DelegatedRole]",
1213+
roles: Dict[str, DelegatedRole],
12151214
unrecognized_fields: Optional[Mapping[str, Any]] = None,
12161215
):
12171216
self.keys = keys
@@ -1233,7 +1232,7 @@ def from_dict(cls, delegations_dict: Dict[str, Any]) -> "Delegations":
12331232
for keyid, key_dict in keys.items():
12341233
keys_res[keyid] = Key.from_dict(keyid, key_dict)
12351234
roles = delegations_dict.pop("roles")
1236-
roles_res: "OrderedDict[str, DelegatedRole]" = OrderedDict()
1235+
roles_res: Dict[str, DelegatedRole] = {}
12371236
for role_dict in roles:
12381237
new_role = DelegatedRole.from_dict(role_dict)
12391238
if new_role.name in roles_res:

0 commit comments

Comments
 (0)