Search code examples
pythontraitsenthought

Traits for SortedListWithKey


I am using a SortedListWithKey class from the new sortedcontainers module (link). Is there a way to adapt the List trait to specify that I want a SortedListWithKey(Instance(SomeClass), key=some_key)?

To be more specific, how can achieve something like:

from traits.api import HasTraits, Instance, SortedListWithKey # i know it cannot really be imported

class MyClass(HasTraits):
    sorted_list = SortedListWithKey(Instance(ElementClass)) 

Solution

  • After looking at your question again, I think what you are looking to for is a way of accessing the SortedListWithKey object as if it were a list and using the Traits or TraitsUI machinery to be able to validate/view/modify it. The Property trait should help here allowing you to view the SortedListWithKey as a list. I have modified my code example below to have another trait be a Property(List(Str)) and view it with a simple TraitsUI:

    from sortedcontainers import SortedListWithKey
    
    from traits.api import Callable, HasTraits, List, Property, Str
    from traitsui.api import Item, View
    
    
    class MyClass(HasTraits):
        sorted_list_object = SortedListWithKey(key='key_func')
    
        sorted_list = Property(List(Str), depends_on='sorted_list_object')
    
        key_func = Callable
    
        def _get_sorted_list(self):
            return list(self.sorted_list_object)
    
        def default_key_func(self):
            def first_two_characters(element):
                return element[:2]
            return first_two_characters
    
        def default_traits_view(self):
            view = View(
                Item('sorted_list', style='readonly')
            )
            return view
    
    
    if __name__ == '__main__':
        example = MyClass()
        example.sorted_list_object = SortedListWithKey(
            ['first', 'second', 'third', 'fourth', 'fifth']
        )
        example.configure_traits()