Skip to content

Commit 6576c7b

Browse files
committed
Performance: remove __missing__() from production, it did repr(self)
Anytime there was a missing dict key (including all fields without "auth"), __missing__() was called and did an repr(self.data) for developer assistance. That happend more then 800 times per request.
1 parent 7c6130e commit 6576c7b

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/schematools/types.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import json
88
import logging
99
import re
10+
import sys
1011
import typing
1112
import warnings
1213
from collections import UserDict
@@ -51,6 +52,12 @@
5152

5253
logger = logging.getLogger(__name__)
5354

55+
IS_DEBUGGER = (
56+
"pytest" in sys.modules
57+
or (sys.stdin and sys.stdin.isatty())
58+
or (hasattr(sys, "gettrace") and sys.gettrace() is not None)
59+
)
60+
5461

5562
class SemVer(str):
5663
"""Semantic version numbers.
@@ -208,8 +215,15 @@ def __deepcopy__(self, memo):
208215
def __repr__(self) -> str:
209216
return f"{self.__class__.__name__}({self.data!r})"
210217

211-
def __missing__(self, key: str) -> NoReturn:
212-
raise KeyError(f"No field named '{key}' exists in {self!r}")
218+
if IS_DEBUGGER:
219+
220+
def __missing__(self, key: str) -> NoReturn:
221+
# This method would also be called by self.get("auth") for example,
222+
# which makes such fail cases a bit slower than they have to be.
223+
raise KeyError(
224+
f"No field named '{key}' exists in {self.__class__.__name__},"
225+
f" available are: {', '.join(self.keys())}"
226+
)
213227

214228

215229
class SchemaType(JsonDict):

0 commit comments

Comments
 (0)