Accessing attributes of the context manager from within a "with" block

Viewed 26

I want to emulate this behavior in my own code:

g = tf.Graph()
with g.as_default():
  c = tf.constant(30.0)
  # How does the tf.constant variable here know to add g as its graph attribute?
  assert c.graph is g

My confusion is that c is somehow able to set g as its graph. I also want to be able to register my own functions with the same pattern as Tensorflow does here:

@tf.function
def add(a, b):
    return a + b
def func

My suspicion is that in the decorator @tf.function that adds a function to Tensorflow, it is able to access attributes of the current context manager. I've been trying to look into how you can reference context managers or attributes of context managers from within the with block but I haven't found it. Does anybody know how I can achieve this desired effect?

0 Answers
Related