ytutow
ytutow

Reputation: 385

Tensorflow: 'tf.get_default_session()` after sess=tf.Session() is None

I was trying to figure out why tf.get_default_session() always returns None type:

import tensorflow as tf

tf.reset_default_graph()
init=tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

default = tf.get_default_session()
default == None # True

I do not know why default = tf.get_default_session() is None since I thought it should return the previous session. Could anyone figures out what's wrong with my code?

Upvotes: 11

Views: 8364

Answers (1)

Maxim
Maxim

Reputation: 53758

Just creating a tf.Session() doesn't make it a default. This is basically the difference between tf.Session and tf.InteractiveSession:

sess = tf.InteractiveSession()
print(tf.get_default_session())    # this is not None!

Unlike tf.InteractiveSession, a tf.Session becomes a default only inside with block (it's a context manager):

sess = tf.Session()
with sess:
  print(tf.get_default_session())  # this is not None!

Upvotes: 17

Related Questions