Speed up import of options.types

The color table attributes are never used in a type checked
environment, only via setattr/gettattr so dont create individual
get/setters for them. Reduaces the import time for this module from 2ms
to 0.7ms

Since attribute access is implemented via __getattr__ there should be no
performance implications for normal attribute access, as __getattr__ is
only called if normal attribute access fails. setattr becomes slightly
slower but that is done very rarely.
This commit is contained in:
Kovid Goyal 2021-06-04 06:01:55 +05:30
parent e10a7579e8
commit 2c9c0751a4
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
2 changed files with 42 additions and 2313 deletions

View File

@ -105,15 +105,6 @@ def generate_class(defn: Definition, loc: str) -> Tuple[str, str]:
tc_imports.add((func.__module__, func.__name__)) tc_imports.add((func.__module__, func.__name__))
cnum = int(option.name[5:]) cnum = int(option.name[5:])
color_table[cnum] = '0x{:06x}'.format(func(option.defval_as_string).__int__()) color_table[cnum] = '0x{:06x}'.format(func(option.defval_as_string).__int__())
a('')
a(' @property')
a(f' def {option.name}(self) -> {typ}:')
a(f' x = self.color_table[{cnum}]')
a(f' return {typ}((x >> 16) & 255, (x >> 8) & 255, x & 255)')
a('')
a(f' @{option.name}.setter')
a(f' def {option.name}(self, val: {typ}) -> None:')
a(f' self.color_table[{cnum}] = val.__int__()')
continue continue
else: else:
func, typ = option_type_data(option) func, typ = option_type_data(option)
@ -234,6 +225,28 @@ def generate_class(defn: Definition, loc: str) -> Tuple[str, str]:
a(' pass') a(' pass')
a(' raise KeyError(f"No option named: {k}")') a(' raise KeyError(f"No option named: {k}")')
if defn.has_color_table:
a('')
a(' def __getattr__(self, key: str) -> typing.Any:')
a(' if key.startswith("color"):')
a(' q = key[5:]')
a(' if q.isdigit():')
a(' k = int(q)')
a(' if 0 <= k <= 255:')
a(' x = self.color_table[k]')
a(' return Color((x >> 16) & 255, (x >> 8) & 255, x & 255)')
a(' raise AttributeError(key)')
a('')
a(' def __setattr__(self, key: str, val: typing.Any) -> typing.Any:')
a(' if key.startswith("color"):')
a(' q = key[5:]')
a(' if q.isdigit():')
a(' k = int(q)')
a(' if 0 <= k <= 255:')
a(' self.color_table[k] = int(val)')
a(' return')
a(' object.__setattr__(self, key, val)')
a('') a('')
a('') a('')
a('defaults = Options()') a('defaults = Options()')

2324
kitty/options/types.py generated

File diff suppressed because it is too large Load Diff