Skip to content

TraitType init_instance should be able to depend on object initialization arguments #90

@NeilGirdhar

Description

@NeilGirdhar

I am trying to replace my traitlet-like system with the traitlets project. I have a number of "Cluster" objects that have a size member, which is provided to the constructor. They contain numpy array traits that should be sized according to this size:

    class ClusterSizedNDArray(NDArray):

        def __init__(self, **metadata):
            super().__init__(cluster_sized=True,
                             shape=(),
                             dtype=np.float64,
                             **metadata)

        def shape(self, obj):
            return (obj.size,) + self.metadata['shape']


    class Cluster(HasTraits):

        signals = ClusterSizedNDArray()

        def __new__(cls, *args, **kw):
            new_meth = super().__new__
            size = kw.pop('size')
            obj = new_meth(cls, **kw)
            # Initialize size before traits are populated that have that size.
            obj.size = size
            return obj

Unfortunately, this doesn't work because obj.size is still not set on the object until after HasTraits.__new__ has been called. What would be a nice way to make this work? Is this something that traitlets can handle or should I implement my own similar system?

Perhaps I should inherit from another class that just sets the size, so that the mro is Cluster, HasTraits, SizeSettingBaseClass?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions