Pekka
Pekka

Reputation: 2448

Why tf.Variable is iterable but can't be iterated

Why this is true:

from collections import Iterable
import tensorflow as tf

v = tf.Variable(1.0)
print(isinstance(v, Iterable))

True

while this

iter(v)

gives

TypeError: 'Variable' object is not iterable.

Upvotes: 3

Views: 2541

Answers (1)

Ali Ismayilov
Ali Ismayilov

Reputation: 1755

I found below method in Tensorflow's Variable class:

def __iter__(self):
    """Dummy method to prevent iteration. Do not call.
    NOTE(mrry): If we register __getitem__ as an overloaded operator,
    Python will valiantly attempt to iterate over the variable's Tensor from 0
    to infinity.  Declaring this method prevents this unintended behavior.
    Raises:
      TypeError: when invoked.
    """
    raise TypeError("'Variable' object is not iterable.")

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/variables.py#L366

Upvotes: 6

Related Questions