[PEAK] trellis attrs

PJ Eby pje at telecommunity.com
Fri Sep 30 17:17:42 EDT 2011


On Fri, Sep 30, 2011 at 4:16 PM, nicky van foreest <vanforeest at gmail.com>wrote:

> Sorry to bug you, but I tried also the following:
>
> class Step(trellis.Component):
>    duration = trellis.attr(0)
>
>    def __init__(self, machine):
>        self.machine = machine
>        self.prevs = trellis.Set([])
>
> instead of
>
> class Step(trellis.Component):
>     prevs = trellis.make(trellis.Set)
>    duration = trellis.attr(0)
>
>     def __init__(self, machine):
>        self.machine = machine
>
> This also works (that is, I get the same schedule in both cases). Is
> there a difference between the two implementations?


The reason that your code currently *appears* to work is because you're not
changing the value of 'prevs' at runtime.

If at some point you did, say, "someStep.prevs = trellis.Set(somedata)",
your program would break because none of the listeners of someStep.prevs
would notice the change.  That's why you should always declare your
attributes using trellis.* descriptors.

The more "correct" (trellisthonic?) way to write your code above is:

class Step(trellis.Component):
    duration = trellis.attr(0)
    prevs = trellis.make(trellis.Set)
    machine = None
    # No __init__ method necessary!

That is, there's no reason to have an __init__ method at all, since
trellis.Component() already takes keyword arguments and assigns them to
attributes, as long as they are defined in the class.



> The second
> implementation sets prevs as a class variable, but this does not
> appear necessary (telling from implementation 1).
>

Please note that 'prevs' is *not* a "class variable".  It's a descriptor.
That is, Step.prevs is a descriptor object, but someStep.prevs (where
someStep is an instance of Step) will be a distinct trellis.Set() instance,
unless overridden when created (e.g. via "someStep=Step(prevs=...)").
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.eby-sarna.com/pipermail/peak/attachments/20110930/1b5ad8a4/attachment-0001.html


More information about the PEAK mailing list