Skip to content
Snippets Groups Projects
Commit a1fe6522 authored by Paul McCarthy's avatar Paul McCarthy
Browse files

A neat little specialised dictionary which allows me to use a particular

class as a key, but where value lookups on subclasses of that class will
still match against that class.
parent 51bf824f
No related branches found
No related tags found
No related merge requests found
......@@ -25,15 +25,86 @@ import fsl.data.image as fslimage
And a second dictionary for tooltips
"""
class _TypeDict(dict):
"""A custom dictionary which allows classes or class instances to be used
as keys for value lookups, but internally transforms any class/instance
keys into strings. Tuple keys are supported. Value assignment with
class/instance keys is not supported.
If a class/instance is passed in as a key, and there is no value
associated with that class, a search is performed on all of the base
classes of that class to see if any values are present for them.
"""
def __getitem__(self, key):
if isinstance(key, type):
key = key.__name__
origKey = key
bases = []
# Make the code a bit easier by
# treating non-tuple keys as tuples
if not isinstance(key, tuple):
key = tuple([key])
newKey = []
# Transform any class/instance elements into
# their string representation (the class name)
for elem in key:
if isinstance(elem, type):
newKey.append(elem.__name__)
bases .append(elem.__bases__)
elif not isinstance(elem, str):
newKey.append(elem.__class__.__name__)
bases .append(elem.__class__.__bases__)
else:
newKey.append(elem)
bases .append(None)
key = newKey
return dict.__getitem__(self, key)
while True:
# If the key was not a tuple turn
# it back into a single element key
# for the lookup
if len(key) == 1: lKey = key[0]
else: lKey = tuple(key)
val = dict.get(self, lKey, None)
if val is not None:
return val
# No more base classes to search for - there
# really is no value associated with this key
elif all([b is None for b in bases]):
raise KeyError(key)
# Search through the base classes to see
# if a value is present for one of them
for i, (elem, elemBases) in enumerate(zip(key, bases)):
if elemBases is None:
continue
# test each of the base classes
# of the current tuple element
for elemBase in elemBases:
newKey = list(key)
newKey[i] = elemBase.__name__
try: return self.__getitem__(tuple(newKey))
except KeyError: continue
# No value for any base classes either
raise KeyError(origKey)
labels = _TypeDict({
'OrthoPanel' : 'Ortho View',
'LightBoxPanel' : 'Lightbox View',
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment