How constant is tf.constant?

AerysS :

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?

francoisr :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386366&siteId=1