TensorFlow
default session
tf.Session()
machine learning
Python

Tensorflow 'tf.get_default_session after sesstf.Session is None

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

In TensorFlow 1.x, creating a session with sess = tf.Session() does not automatically make it the default session. A default session exists only inside an active session context such as with sess.as_default():, which is why tf.get_default_session() can still return None even though you already created a session object.

Why tf.get_default_session() Returns None

TensorFlow 1.x keeps a thread-local stack of default sessions. Assigning a session to a Python variable does not push it onto that stack.

This means:

python
1import tensorflow as tf
2
3a = tf.constant(3)
4sess = tf.Session()
5
6print(tf.get_default_session())  # None
7print(sess.run(a))               # 3

The session exists, and you can run tensors through it explicitly, but TensorFlow has no active default session in the current context.

Use sess.as_default()

If you want APIs that rely on the default session, enter a default-session context:

python
1import tensorflow as tf
2
3a = tf.constant(10)
4sess = tf.Session()
5
6with sess.as_default():
7    print(tf.get_default_session() is sess)  # True
8    print(a.eval())                          # 10

Inside that with block, tf.get_default_session() returns the session you activated.

Why .eval() Often Triggers the Confusion

Many TensorFlow 1.x examples use .eval() on tensors:

python
print(a.eval())

But .eval() depends on there being a default session. If you did not enter a with sess.as_default(): block, it will fail even though sess.run(a) works.

That difference is what confuses many people:

  • 'sess.run(tensor) uses the explicit session you pass'
  • 'tensor.eval() expects a default session to already exist'

Graph and Session Scope Must Match

In TensorFlow 1.x, sessions are bound to graphs. If you are working with multiple graphs, the default graph and default session must line up:

python
1import tensorflow as tf
2
3graph = tf.Graph()
4with graph.as_default():
5    x = tf.constant(5)
6    with tf.Session(graph=graph) as sess:
7        with sess.as_default():
8            print(tf.get_default_graph() is graph)
9            print(tf.get_default_session() is sess)
10            print(x.eval())

Mixing tensors from one graph with a session created for another graph produces opaque runtime errors.

The Safer Pattern: Pass the Session Explicitly

Legacy TensorFlow code is usually easier to reason about when functions receive the session explicitly:

python
1def evaluate_tensor(sess, tensor):
2    return sess.run(tensor)
3
4with tf.Session() as sess:
5    y = tf.constant([1, 2, 3])
6    print(evaluate_tensor(sess, y))

This avoids hidden dependencies on global default session state.

Modern TensorFlow Usually Does Not Use Sessions

TensorFlow 2 uses eager execution by default, so most new code does not need session APIs at all:

python
1import tensorflow as tf
2
3x = tf.constant([1.0, 2.0, 3.0])
4print(x.numpy())

If you are maintaining TensorFlow 1.x-style code under TensorFlow 2, you may still encounter tf.compat.v1.Session() and related compatibility APIs. But for new code, session management is usually legacy behavior, not the recommended model.

Clean Up Sessions

Sessions own runtime resources, so close them or use a context manager:

python
with tf.Session() as sess:
    z = tf.random_normal([1000, 1000])
    _ = sess.run(z)

That pattern prevents resource leaks in loops and training scripts.

Common Pitfalls

  • Expecting sess = tf.Session() to automatically define the default session.
  • Calling .eval() outside a with sess.as_default(): context.
  • Mixing graph scope and session scope incorrectly.
  • Hiding session dependencies in helpers instead of passing the session explicitly.
  • Writing new TensorFlow 2 code as if TensorFlow 1.x session patterns were still the normal default.

Summary

  • In TensorFlow 1.x, creating a session and making it the default are different things.
  • 'tf.get_default_session() returns None until a default-session context is active.'
  • Use with sess.as_default(): when code depends on a default session.
  • Prefer explicit sess.run(...) or explicit session parameters in legacy code.
  • In TensorFlow 2, sessions are mostly legacy compatibility tools rather than the standard programming model.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.