Unlike tf.constant(), a Variable's value can be changed after creation via methods like .assign(), .assign_add(), and .assign_sub(), which update its stored value in place rather than creating a brand-new tensor — this in-place mutability is exactly what lets an optimizer repeatedly nudge a model's weights during training. The trainable parameter, True by default, controls whether TensorFlow's automatic differentiation should track this variable for gradient computation; setting it to False creates a variable that persists and can still be manually updated, but is excluded from gradient-based training.
1Understanding tf.Variable()
Unlike tf.constant(), a Variable's value can be changed after creation via methods like .assign(), .assign_add(), and .assign_sub(), which update its stored value in place rather than creating a brand-new tensor — this in-place mutability is exactly what lets an optimizer repeatedly nudge a model's weights during training. The trainable parameter, True by default, controls whether TensorFlow's automatic differentiation should track this variable for gradient computation; setting it to False creates a variable that persists and can still be manually updated, but is excluded from gradient-based training.
Use .assign(), or .assign_add()/.assign_sub(), to update a Variable's value in place — a plain Python reassignment doesn't update the Variable at all, it just rebinds the Python name to point at something else entirely.
import tensorflow as tf
weight = tf.Variable(5.0)
weight.assign(10.0)
print(weight)2Practical Example
Here is a real-world application of tf.Variable() showing how it is used in production TensorFlow code.
import tensorflow as tf
counter = tf.Variable(0)
counter.assign_add(1)
counter.assign_add(1)
print(counter.numpy())3Best Practices
Follow these guidelines when working with tf.Variable():
1. Use .assign()/.assign_add()/.assign_sub() to update a Variable's value in place, never a plain Python reassignment, which doesn't actually mutate the underlying Variable
2. Set trainable=False for variables that need to persist and update manually but shouldn't be included in gradient-based optimization, like a manually-tracked running statistic
3. Let Keras layers create and manage their own Variables automatically in most cases, rather than manually creating tf.Variable() objects for standard model weights
Tip: Use .assign(), or .assign_add()/.assign_sub(), to update a Variable's value in place — a plain Python reassignment doesn't update the Variable at all, it just rebinds the Python name to point at something else entirely.
import tensorflow as tf
weight = tf.Variable(5.0)
weight.assign(10.0)
print(weight)