Swap order of imports to avoid needlessly throwing ImportError all the time, and cache as much as we can (imported classes, keys)

This commit is contained in:
Stephen Boddy 2011-02-17 02:28:38 +01:00
parent ff017ea26d
commit 03791c753b
1 changed files with 20 additions and 8 deletions

View File

@ -33,6 +33,9 @@ class Factory(Borg):
'Notebook': 'notebook', 'Notebook': 'notebook',
'Container': 'container', 'Container': 'container',
'Window': 'window'} 'Window': 'window'}
types_keys = types.keys()
instance_types = {}
instance_types_keys = []
def __init__(self): def __init__(self):
"""Class initialiser""" """Class initialiser"""
@ -45,16 +48,25 @@ class Factory(Borg):
def isinstance(self, product, classtype): def isinstance(self, product, classtype):
"""Check if a given product is a particular type of object""" """Check if a given product is a particular type of object"""
if classtype in self.types.keys(): if classtype in self.types_keys:
# This is quite ugly, but we're importing from the current # This is now very ugly, but now it's fast :-)
# directory if that makes sense, otherwise falling back to # Someone with real Python skills should fix this to be less insane.
# terminatorlib. Someone with real Python skills should fix # Optimisations:
# this to be less insane. # - swap order of imports, otherwise we throw ImportError
# almost every time
# - cache everything we can
try: try:
module = __import__(self.types[classtype], None, None, ['']) type_key = 'terminatorlib.%s' % self.types[classtype]
if type_key not in self.instance_types_keys:
self.instance_types[type_key] = __import__(type_key, None, None, [''])
self.instance_types_keys.append(type_key)
module = self.instance_types[type_key]
except ImportError: except ImportError:
module = __import__('terminatorlib.%s' % self.types[classtype], type_key = self.types[classtype]
None, None, ['']) if type_key not in self.instance_types_keys:
self.instance_types[type_key] = __import__(type_key, None, None, [''])
self.instance_types_keys.append(type_key)
module = self.instance_types[type_key]
return(isinstance(product, getattr(module, classtype))) return(isinstance(product, getattr(module, classtype)))
else: else:
err('Factory::isinstance: unknown class type: %s' % classtype) err('Factory::isinstance: unknown class type: %s' % classtype)