pythontraitsenthoughttraitsui

How do I update the dictionary of a mapped trait, after I've already constructed it?


I need to update the dictionary of a mapped trait some time after initial trait creation. How do I do this? The following code:

from traits.api import (HasTraits, Trait)

class bar(HasTraits):
    zap = Trait("None", {"None": None})

    def __init__(self):
        # In reality, determined programmatically at runtime.
        add_dict_entries = {"One": 1}
        new_dict = {"None": None}
        new_dict.update(add_dict_entries)
        self.zap = Trait("None", new_dict)

theBar = bar()

yields:

Traceback (most recent call last):
  File "tst_mapped_trait.py", line 13, in <module>
    theBar = bar()
  File "tst_mapped_trait.py", line 11, in __init__
    self.zap = Trait("None", new_dict)
  File "C:\Users\dbanas\Anaconda3\envs\pybert-dev\lib\site-packages\traits\trait_handlers.py", line 236, in error
    object, name, self.full_info(object, name, value), value
traits.trait_errors.TraitError: The 'zap' trait of a bar instance must be 'None', but a value of <traits.traits.CTrait object at 0x00000000034AA9E8> <class 'traits.traits.CTrait'> was specified.```


Solution

  • Okay, the following code worked:

    from traits.api import (HasTraits, Trait)
    
    class bar(HasTraits):
        zap = Trait("None", {"None": None})
    
        def __init__(self):
            # In reality, determined programmatically at runtime.
            add_dict_entries = {"One": 1}
            new_dict = {"None": None}
            new_dict.update(add_dict_entries)
            # self.zap = Trait("None", new_dict)
            # self.zap.update(new_dict)
            # self.trait_setq(zap=Trait("None", new_dict))
            self.remove_trait("zap")
            self.add_trait("zap", Trait("None", new_dict))
    
    theBar = bar()
    

    Note: The commented out lines are things I tried, which did not work.