0

I came across the following expression in python. I believe the expression itself is legit and how it constructs actually makes sense. But still, from strongly typed background, I am wondering if people typically do that in python ... i.e. using the same class expressing two quite different concept (data vs data size meta data)

class AttentionDecoderOutput(
    namedtuple("DecoderOutput", [
        "logits", "predicted_ids", "cell_output", "attention_scores",
        "attention_context"
    ])):
  """Augmented decoder output that also includes the attention scores.
  """
  pass

AttentionDecoderOutput defines a data structure. The output_size below defines the size of each element in the namedtuple.

def output_size(self):
  return AttentionDecoderOutput(
    logits=self.vocab_size,
    predicted_ids=tf.TensorShape([]),
    cell_output=self.cell.output_size,
    attention_scores=tf.shape(self.attention_values)[1:-1],
    attention_context=self.attention_values.get_shape()[-1])
  • So, this is actually a poorly extended `namedtuple`. It doesn't define a slots, so now `AttentionDecoderOutput` has a `dict` attached to it. It seems entirely pointless to be deriving from this class, and then simply using `pass`. – juanpa.arrivillaga Jul 05 '17 at 18:19
  • it's just a more abstract object, is it not? there are situations where that is convenient – Alter Jul 05 '17 at 18:22
  • It seems to me, what you really want is just `AttentionDecoderOutput = namedtuple("AttentionDecoderOutput", ["logits", "predicted_ids", "cell_output", "attention_scores", "attention_context"])` .... `namedtuple` is a *class factory* after all... – juanpa.arrivillaga Jul 05 '17 at 18:22
  • Unless you want `AttentionDecoderOutput` to derive from `DecoderOutput`, but the way this is written, `DecoderOutput` is a one-off class that is created and used as a base-class, but isn't accessible from anywhere else. – juanpa.arrivillaga Jul 05 '17 at 18:23
  • So, to properly sublcass a `namedtuple` takes a bit more work than just `class DerivedNamedTuple(SomeOtherNamedTuple): pass`. Take a look at the example in the docs: https://docs.python.org/3.6/library/collections.html#collections.namedtuple And this answer here, which details how a well-behaved subclass would have to be implemented: https://stackoverflow.com/a/28500620/5014455 – juanpa.arrivillaga Jul 05 '17 at 18:25

0 Answers0