2

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?

Vlad
  • 8,225
  • 5
  • 33
  • 45
Minh-Long Luu
  • 2,393
  • 1
  • 17
  • 39
  • constant is to be seen as in a mathematical sense (in contrast to a variable for example that you need to find or optimize) not in a informatic sense. It is not a `const int `, or whatever, if you know the C language. – J.Zagdoun Mar 30 '20 at 12:31

2 Answers2

2

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.

Vlad
  • 8,225
  • 5
  • 33
  • 45
2

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.

francoisr
  • 4,407
  • 1
  • 28
  • 48