module 'tensorflow' has no attribute 'Session' (tested fix)

AttributeError: module 'tensorflow' has no attribute 'Session' (also 'placeholder', 'global_variables_initializer', 'get_default_graph') means TF 1.x code is running on TensorFlow 2. Rewrite it as eager code / @tf.function, or use tf.compat.v1 with eager execution disabled. Both run below on TF 2.21.

1. Reproduce

import tensorflow as tf

for name in ["Session", "placeholder", "global_variables_initializer", "get_default_graph"]:
    try:
        getattr(tf, name)
    except AttributeError as e:
        print("AttributeError:", e)
AttributeError: module 'tensorflow' has no attribute 'Session'
AttributeError: module 'tensorflow' has no attribute 'placeholder'
AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'

These are TensorFlow 1.x APIs. TensorFlow 2 runs eagerly by default and moved them under tf.compat.v1, so code (or a tutorial) written for TF 1 fails on the first tf.Session() or tf.placeholder.

2. Fix: rewrite for TF2, or use tf.compat.v1

import tensorflow as tf

# Option A (recommended): TF2 eager code, no Session at all
a = tf.constant(2.0)
print("eager:", float(a * 3))

@tf.function           # graph speed without a Session
def f(x):
    return x * 3
print("tf.function:", float(f(a)))

# Option B (legacy code you cannot rewrite yet): tf.compat.v1
tf.compat.v1.disable_eager_execution()
x = tf.compat.v1.placeholder(tf.float32, shape=())
y = x * 3
with tf.compat.v1.Session() as sess:
    print("compat.v1 Session:", sess.run(y, feed_dict={x: 2.0}))
eager: 6.0
tf.function: 6.0
compat.v1 Session: 6.0

Related: tf.function retracing warning, AttributeError: module has no attribute.

Frequently asked questions

Why does TensorFlow have no attribute Session?

tf.Session is a TensorFlow 1.x API. In TensorFlow 2 it only exists as tf.compat.v1.Session.

How do I replace tf.placeholder in TensorFlow 2?

Pass the data as a normal function argument (optionally in a @tf.function), or use tf.compat.v1.placeholder after tf.compat.v1.disable_eager_execution().

Do I need global_variables_initializer in TF2?

No. tf.Variable values are initialized when created in eager mode.

Written with AI assistance. Measured on 2026-10-24 with tensorflow-cpu 2.21.0 and Python 3.13.5 on Linux. The scripts ran verbatim and the output was pasted unedited (TensorFlow startup log lines filtered). PlainTables is our extension; TensorFlow is free.