Minh-Long Luu
Minh-Long Luu

Reputation: 2741

How constant is tf.constant?

According to other StackOverFlow questions, you cannot change tf.constant, but when I do this it runs perfectly:

>>>c = tf.constant([2])
>>>c += 1
>>>print(c)
[3]

Why is that?

Upvotes: 2

Views: 201

Answers (2)

francoisr
francoisr

Reputation: 4595

It's still a constant in the sense that you cannot assign to it. Running c += 1 just change the object that c points to like c = c + 1.

c = tf.constant(2)
print(id(c)) # "Address" is 140481630446312 (for my run)
c += 1
print(id(c)) # "Address" is different

but this fails everytime: c.assign(2)

This is not a limitation of Tensorflow, but of Python itself. Since it's not compiled, we can't check for constants. The best you can do these days is use a type hint (Python 3.6+) to signify to IDEs and optional static typecheckers that you don't want a variable to be reassigned. See this answer for details.

Upvotes: 2

Vlad
Vlad

Reputation: 8595

The original c is constant and remains unchanged. You loose reference to it by creating a new tensor with the same name c that equals to the old value of c plus 1.

Upvotes: 2

Related Questions