Attributeerror: nonetype object has no attribute shape

In this article, we will show you how to solve the error attributeerror: 'nonetype' object has no attribute 'shape'. What does this error indicate and why does it occur? If you have that thought in your mind, read through to the end of this article to find the answer.

The error attributeerror: nonetype object has no attribute shape is an error in Python that occurs when you attempt to access the shape() attribute of an object that has a “None” value.

It just means that this error indicates that you attempted to carry out an action that needs the input data to have a specified shape, but that operation failed because the data had a value of None and hence lacked a shape attribute.

Before we begin our tutorial, have a quick overview of Python and AttributeError.

What is Python?

Python is one of the most popular programming languages. It is used for developing a wide range of applications. It is a high-level programming language that is usually used by developers nowadays due to its flexibility.

What is AttributeError?

An attributeerror is an error that appears in our Python codes when we try to access an attribute of a non-existent object. In addition, this occurs when we attempt to perform non-supported operations.

Now that we understand this error and even what Python and an AttributeError are, let’s move on to our “how to fix this error” tutorial.

How to solve “nonetype object has no attribute shape” in Python

Time needed: 2 minutes

The following is a step-by-step guide to resolve the Python error attributeerror: nonetype object has no attribute shape.

  1. Check the input data.

    The first step is to use the if statement to check if the input data isn’t “None” before accessing the attributes.

  2. Put the variable on an appropriate object.

    The next step is to put the variable on an appropriate object before accessing its attributes if the variable is None.

  3. Use the try-except block.

    To get and handle the attributeerror, you can use the try-except block, where you can print an error message.

Example:

import numpy as np

sample_data = None

if sample_data is not None:
    shape = sample_data.shape
    print("Shape of data:", shape)
else:
    print("Sample input data is None.")

if sample_data is None:
    sample_data = np.zeros((7, 13))
try:
    shape = sample_data.shape
    print("Shape of data:", shape)
except AttributeError:
    print("Sample input data has no shape attribute.")

Output:

Sample input data is None.
Shape of data: (7, 13)

Why “NoneType has no attribute X” happens

This AttributeError fires when a variable is None but you try to call a method or access a property on it. Python’s None is a distinct type with only a handful of attributes — no user methods exist on it. Any dotted access on None raises AttributeError.

Common triggers

  • Function returned None implicitly. A function without an explicit return statement falls through to None. Missing else branches, filter results, and lookup misses are common sources.
  • Method chaining on mutating operations. list.sort(), list.append(), and set.add() return None — they mutate in place. Chaining my_list.sort().reverse() fails.
  • Dictionary lookups with missing keys. my_dict.get(key) returns None if the key is missing. Always provide a default: my_dict.get(key, default).
  • Regex match returned None. re.match returns None when no match. Guard before calling .group().
  • Failed database queries. ORM .first() and .find_one() return None on empty results.

Diagnostic pattern

# BAD — no defensive check
def get_user_config(user_id):
    return db.query(User).filter_by(id=user_id).first()

user = get_user_config(42)
name = user.name  # AttributeError: 'NoneType' object has no attribute 'name'

# GOOD — guard for None, fail fast with a clear message
def get_user_config(user_id):
    user = db.query(User).filter_by(id=user_id).first()
    if user is None:
        raise ValueError(f"User not found: {user_id}")
    return user

# Or use Optional pattern
from typing import Optional
def get_user_config(user_id) -> Optional[User]:
    return db.query(User).filter_by(id=user_id).first()

user = get_user_config(42)
if user is not None:
    name = user.name

Best practices

  • Use Optional type hints. Signal that a function may return None so callers must handle it.
  • Fail fast at boundaries. Raise a clear exception in helper functions instead of returning None silently.
  • Use mypy or Pyright. Static type checkers catch NoneType errors before runtime.
  • Guard with “is not None”. Explicit is None checks are the Pythonic way, not if x: (fails on 0 and empty strings).

Frequently Asked Questions

What is Python AttributeError and what causes it?

AttributeError is raised when you access an attribute or method that doesn’t exist on the object. Most common cause: calling a method on None (NoneType has no attribute X). Other causes: typo in method name, wrong object type (str when you expected list), or using a feature removed in a newer library version. The error names exactly which type and which missing attribute.

How do I fix ‘NoneType object has no attribute’?

The variable you’re accessing is None, but you expected an object. Trace back to where it was assigned: a function returning None instead of an object (forgot to return), a database query returning no rows (Model.objects.first() returns None when empty), or an API call that failed silently. Safe pattern: if obj is not None: obj.method() OR use the walrus operator: if (obj := get_obj()): obj.method().

How do I check if an attribute exists before accessing it?

Use hasattr(obj, ‘attr_name’) for runtime check, or getattr(obj, ‘attr_name’, default) to get-with-default. For frequent attribute checks, consider type hints + mypy/pyright which catch most AttributeErrors at static-analysis time before runtime.

How do I prevent AttributeError from None values?

Three patterns: (1) Always validate function returns (if result is None: raise). (2) Use type hints with Optional[X] to make None-ability explicit. (3) Use the walrus operator + early return: if (val := get_val()) is None: return default; use val. Defensive coding around None-able returns prevents 90% of AttributeError in production.

Where can I find more AttributeError fixes?

Browse the AttributeError reference hub for 170+ specific fixes (NoneType, pandas, NumPy, sklearn, Selenium). For related errors see TypeError. For Python debugging fundamentals see Python Tutorial hub.

Conclusion

In conclusion, the Python error attributeerror: 'nonetype' object has no attribute 'shape' can be easily solved by making sure that the input data isn’t None before accessing the attributes.

By following the guide above, there’s no doubt that you’ll be able to resolve this error quickly and without a hassle.

I think that’s all for today, ITSOURCECODERS! We hope you’ve learned a lot from this. If you have any questions or suggestions, please leave a comment below, and for more attributeerror tutorials in Python, visit our website.

Thank you for reading!

Elijah Galero


Programmer & Technical Writer at PIES IT Solution

Elijah Galero is a programmer and writer at PIES IT Solution, author of 175+ tutorials at itsourcecode.com. Specializes in Python error debugging (AttributeError, TypeError, ModuleNotFoundError), Python programming tutorials, and Microsoft Excel how-to guides for BSIT students and productivity learners.

Expertise: Python · Python Errors · Python AttributeError · Python TypeError · ModuleNotFoundError · MS Excel · MS PowerPoint
 · View all posts by Elijah Galero →

Leave a Comment