Python
TensorFlow
Troubleshooting
Programming
Machine Learning

python3 recognizes tensorflow, but doesn't recognize any of its attributes

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

When import tensorflow succeeds but accessing attributes like tf.keras, tf.constant, or tf.Session raises AttributeError, it usually means Python is importing a different module named tensorflow instead of the real package — typically a local file named tensorflow.py in your project directory. Other causes include corrupted installations, version mismatches (TF1 vs TF2 API differences), and virtual environment issues. The fix is to remove any local tensorflow.py file, reinstall TensorFlow in a clean environment, and verify the import path.

Cause 1: Local File Named tensorflow.py

The most common cause is having a file named tensorflow.py in your project directory. Python imports from the current directory before site-packages:

python
1# If you have a file called tensorflow.py in your project:
2import tensorflow as tf
3print(tf.__file__)
4# Output: ./tensorflow.py  <-- WRONG (your local file)
5# Expected: /usr/lib/python3.10/site-packages/tensorflow/__init__.py
6
7tf.constant(5)
8# AttributeError: module 'tensorflow' has no attribute 'constant'

Fix

bash
1# Check which module is loaded
2python3 -c "import tensorflow; print(tensorflow.__file__)"
3
4# Remove the local file and its cache
5rm tensorflow.py
6rm -rf __pycache__/tensorflow*
7
8# Verify
9python3 -c "import tensorflow as tf; print(tf.__version__)"

Cause 2: Corrupted Installation

A partially installed or corrupted TensorFlow package can import without errors but have missing attributes:

bash
1# Uninstall completely and reinstall
2pip3 uninstall tensorflow tensorflow-gpu tensorflow-estimator tensorflow-io -y
3pip3 cache purge
4pip3 install tensorflow
5
6# Verify installation
7python3 -c "import tensorflow as tf; print(tf.__version__); print(tf.reduce_sum([1, 2, 3]))"

For GPU support:

bash
1pip3 install tensorflow[and-cuda]
2
3# Check GPU availability
4python3 -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"

Cause 3: TensorFlow 1.x vs 2.x API Differences

TensorFlow 2.x removed or moved many TF1 attributes. Code written for TF1 raises AttributeError on TF2:

python
1import tensorflow as tf
2
3# TF1 code that fails on TF2
4sess = tf.Session()          # AttributeError in TF2
5placeholder = tf.placeholder(tf.float32)  # AttributeError in TF2
6
7# TF2 equivalents
8# tf.Session() → Eager execution is default, no session needed
9result = tf.constant(5) + tf.constant(3)
10print(result.numpy())  # 8
11
12# tf.placeholder → Use tf.function with input signatures
13@tf.function(input_signature=[tf.TensorSpec(shape=(), dtype=tf.float32)])
14def add_one(x):
15    return x + 1
16
17print(add_one(tf.constant(5.0)))

Using TF1 Compatibility Mode

python
1import tensorflow.compat.v1 as tf
2tf.disable_v2_behavior()
3
4# TF1 code now works
5sess = tf.Session()
6x = tf.placeholder(tf.float32)
7result = sess.run(x + 1, feed_dict={x: 5.0})
8print(result)  # 6.0

Cause 4: Wrong Python or Virtual Environment

TensorFlow may be installed in a different Python version or virtual environment than the one you are running:

bash
1# Check which python and pip are active
2which python3
3which pip3
4
5# Ensure pip installs to the same python
6python3 -m pip install tensorflow
7
8# Verify
9python3 -m pip show tensorflow
bash
1# Create a clean virtual environment
2python3 -m venv tf_env
3source tf_env/bin/activate
4pip install tensorflow
5
6python3 -c "import tensorflow as tf; print(tf.__version__); print(dir(tf)[:10])"

Cause 5: Namespace Package Conflicts

Another package or directory named tensorflow in sys.path can shadow the real package:

python
1import sys
2print('\n'.join(sys.path))
3
4# Look for unexpected directories that might contain a tensorflow module
5# Remove or rename any conflicting package
bash
1# Check for other tensorflow-related packages
2pip3 list | grep tensor
3
4# If tensorflow-gpu and tensorflow are both installed, remove one
5pip3 uninstall tensorflow-gpu
6pip3 install tensorflow

Diagnostic Script

Run this script to identify the root cause:

python
1import sys
2print(f"Python: {sys.executable}")
3print(f"Version: {sys.version}")
4print(f"Path: {sys.path[:3]}")
5
6try:
7    import tensorflow as tf
8    print(f"\ntf.__file__: {tf.__file__}")
9    print(f"tf.__version__: {tf.__version__}")
10    print(f"Has keras: {hasattr(tf, 'keras')}")
11    print(f"Has constant: {hasattr(tf, 'constant')}")
12    print(f"Has reduce_sum: {hasattr(tf, 'reduce_sum')}")
13except AttributeError as e:
14    print(f"\nAttributeError: {e}")
15    print(f"tf.__file__: {tf.__file__}")
16    print("This is likely a local file shadowing the real TensorFlow package")
17except ImportError as e:
18    print(f"\nImportError: {e}")
19    print("TensorFlow is not installed in this environment")

Common Pitfalls

  • Having a file named tensorflow.py in the project directory: Python's import system searches the current directory first. A local tensorflow.py or tensorflow/ directory shadows the real package. Rename the file and delete __pycache__/tensorflow*.
  • Using TF1 API calls in TensorFlow 2.x: tf.Session, tf.placeholder, tf.global_variables_initializer were removed in TF2. Use tensorflow.compat.v1 for legacy code or rewrite using TF2's eager execution and tf.function.
  • Installing TensorFlow with pip but running with a different Python: pip install targets one Python interpreter. If you have multiple Python versions, use python3 -m pip install tensorflow to ensure the package is installed for the correct interpreter.
  • Not restarting the Python interpreter or Jupyter kernel after reinstalling: Python caches modules in memory. After reinstalling TensorFlow, restart the Python process or restart the Jupyter kernel to pick up the new installation.
  • Installing both tensorflow and tensorflow-gpu: In TensorFlow 2.x, tensorflow includes GPU support. Installing both packages can cause conflicts. Uninstall tensorflow-gpu and use only tensorflow (with tensorflow[and-cuda] for GPU).

Summary

  • Check tf.__file__ to verify you are importing the real TensorFlow package, not a local file
  • Remove any tensorflow.py file and __pycache__/tensorflow* in your project directory
  • Use python3 -m pip install tensorflow in a clean virtual environment for a fresh install
  • For TF1 code on TF2, use tensorflow.compat.v1 or rewrite using TF2 APIs
  • Run the diagnostic script to quickly identify import path issues, version mismatches, and missing attributes

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.