Skip to content

Commit f42e75f

Browse files
committed
feat: cache error and null result formatters
1 parent 3e95a9a commit f42e75f

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

web3/_utils/method_formatters.py

+20-6
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,11 @@
116116

117117
TValue = TypeVar("TValue")
118118

119+
CachedFormatters = Dict[
120+
Union[RPCEndpoint, Callable[..., RPCEndpoint]],
121+
Callable[[RPCResponse], Any],
122+
]
123+
119124

120125
def bytes_to_ascii(value: bytes) -> str:
121126
return codecs.decode(value, "ascii")
@@ -1209,19 +1214,28 @@ def get_result_formatters(
12091214
return compose(*partial_formatters, *formatters)
12101215

12111216

1217+
_error_formatters: CachedFormatters = {}
1218+
12121219
def get_error_formatters(
12131220
method_name: Union[RPCEndpoint, Callable[..., RPCEndpoint]]
12141221
) -> Callable[[RPCResponse], Any]:
12151222
# Note error formatters work on the full response dict
1216-
error_formatter_maps = (ERROR_FORMATTERS,)
1217-
formatters = combine_formatters(error_formatter_maps, method_name)
1223+
formatters = _error_formatters.get(method_name)
1224+
if formatters is None:
1225+
formatters = _error_formatters[method_name] = compose(
1226+
*combine_formatters((ERROR_FORMATTERS,), method_name)
1227+
)
1228+
return formatters
12181229

1219-
return compose(*formatters)
12201230

1231+
_null_result_formatters: CachedFormatters = {}
12211232

12221233
def get_null_result_formatters(
12231234
method_name: Union[RPCEndpoint, Callable[..., RPCEndpoint]]
12241235
) -> Callable[[RPCResponse], Any]:
1225-
formatters = combine_formatters((NULL_RESULT_FORMATTERS,), method_name)
1226-
1227-
return compose(*formatters)
1236+
formatters = _null_result_formatters.get(method_name)
1237+
if formatters is None:
1238+
formatters = _null_result_formatters[method_name] = compose(
1239+
*combine_formatters((NULL_RESULT_FORMATTERS,), method_name)
1240+
)
1241+
return formatters

0 commit comments

Comments
 (0)