Skip to content

Commit a723554

Browse files
committed
Only initialize the method dispatcher once
This has a _significant_ effect on parser creation time
1 parent 1176bf2 commit a723554

File tree

2 files changed

+373
-291
lines changed

2 files changed

+373
-291
lines changed

html5lib/_utils.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
from types import ModuleType
44

5+
try:
6+
from collections.abc import Mapping
7+
except ImportError:
8+
from collections import Mapping
9+
510
from six import text_type
611

712
try:
@@ -65,6 +70,41 @@ def __getitem__(self, key):
6570
return dict.get(self, key, self.default)
6671

6772

73+
class BoundMethodDispatcher(Mapping):
74+
def __init__(self, instance, dispatcher):
75+
self.instance = instance
76+
self.dispatcher = dispatcher
77+
self.cache = {}
78+
79+
def __getitem__(self, key):
80+
if key in self.cache:
81+
return self.cache[key]
82+
83+
try:
84+
item = self.dispatcher[key]
85+
except KeyError:
86+
item = self.default
87+
88+
r = item.__get__(self.instance)
89+
self.cache[key] = r
90+
return r
91+
92+
def get(self, key, default):
93+
if key in self.dispatcher:
94+
return self[key]
95+
else:
96+
return default
97+
98+
def __iter__(self):
99+
return iter(self.dispatcher)
100+
101+
def __len__(self):
102+
return len(self.dispatcher)
103+
104+
def __contains__(self, key):
105+
return key in self.dispatcher
106+
107+
68108
# Some utility functions to deal with weirdness around UCS2 vs UCS4
69109
# python builds
70110

0 commit comments

Comments
 (0)