Skip to content

Commit

Permalink
Use a defaultdict for Options.data
Browse files Browse the repository at this point in the history
This allows us to remove some `if code not in self.data` checks, but
also requires that we add one.
  • Loading branch information
Boolean263 authored and Flameeyes committed Jul 15, 2020
1 parent 78c4d52 commit 96ff792
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions pcapng/structs.py
Expand Up @@ -5,6 +5,7 @@
import abc
import struct
import warnings
from collections import defaultdict
from collections.abc import Iterable, Mapping

from pcapng import strictness as strictness
Expand Down Expand Up @@ -707,7 +708,7 @@ class Options(Mapping):
def __init__(self, schema, data, endianness):
self.schema = {} # Schema of option fields: {<code>: Option(...)}
self._field_names = {} # Map names to codes
self.data = {} # option data, with numeric option IDs as keys
self.data = defaultdict(list) # option data, with numeric option IDs as keys
self.endianness = endianness # one of '<>!='

# This is the default schema, common to all objects
Expand Down Expand Up @@ -736,6 +737,10 @@ def __eq__(self, other):

def __getitem__(self, name):
code = self._resolve_name(name)
if code not in self.data:
# The defaultdict would create an empty entry if we just let this slide.
# `tests/test_structs.py` expects a KeyError to be raised here instead.
raise KeyError(name)
return self.data[code][0]

def __len__(self):
Expand Down Expand Up @@ -791,8 +796,6 @@ def iter_all_items(self):
def add(self, name, value):
"""Add a value to the given-named option"""
code = self._resolve_name(name)
if code not in self.data:
self.data[code] = []
self.data[code].append(value)
self._check_multiples(code)

Expand All @@ -808,8 +811,6 @@ def _update_data(self, data):
return

for code, value in data:
if code not in self.data:
self.data[code] = []
self.data[code].append(self._decode(code, value))
if len(self.data[code]) > 1 and not self.schema[code].multiple:
try:
Expand Down

0 comments on commit 96ff792

Please sign in to comment.