traits icon indicating copy to clipboard operation
traits copied to clipboard

Proposal: add a generic callable default type and remove TraitListObject etc. special casing

Open corranwebster opened this issue 2 years ago • 1 comments

When generating traits defaults, the key method that is used is the default_value_for method in ctraits.c which is given the trait, object and trait name, gets the default value and type from the trait, and then switches on the type. An obvious thing to do would be to provide a default type where this information is simply passed straight through to an arbitrary callable, which then has precisely as much information as the default value infrastructure, and thus allows replacement with any needed alternative.

While a nice idea in the abstract, this would permit removal of the special-casing of List, Dict and Set trait defaults. Currently trait lists, sets and dicts have special-cased default value types which call the appropriate class with the ctrait, the HasTraits object the name of the trait, and a default value extracted from the trait.

Given the generic callable, these can be replaced with a callable that looks something like:

def trait_list_default(ctrait, object, name):
    value = ctrait.default_value
    trait = ctrait.handler
    return TraitListObject(trait, object, name, value)

corranwebster avatar Nov 29 '21 11:11 corranwebster

Adding a note here if we ever do this: care would be needed to handle what to do when cloning such a trait with a new default value, as well as what to do for subclassing with a new value.

corranwebster avatar May 20 '22 12:05 corranwebster