And And - 3 months ago 20
Python Question

Is it possible to re-enter an existing name scope in TensorFlow?

Entering a name scope of the same name twice:

c = tf.constant(1)
with tf.name_scope("test"):
a = tf.add(c, c)
with tf.name_scope("test"):
b = tf.add(a, a)


results in two name scopes being created:
test
and
test_1
.

Is it possible to re-enter a scope in a separate context manager instead of creating a new one?

Answer

While the solution you suggested in your answer will work today, it relies on an internal implementation detail of tf.name_scope(), and so might not always work. Instead, the recommended way to re-enter a scope is to capture it in the first with statement, and use that value in the second one, as follows:

c = tf.constant(1)
with tf.name_scope("test") as scope:
    a = tf.add(c, c)
with tf.name_scope(scope):
    b = tf.add(a, a)

You can also pass the captured scope as the name of an operator, which is how we typically represent the output of a function that is build from a composition of other operators:

c = tf.constant(1)
with tf.name_scope("test") as scope:
    a = tf.add(c, c)
return tf.add(a, a, name=scope)  # return value gets the scope prefix as its name.
Comments