Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-48650][PYTHON] Display correct call site from IPython Notebook #47009

Closed
wants to merge 6 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions python/pyspark/errors/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import os
import threading
from typing import Any, Callable, Dict, Match, TypeVar, Type, Optional, TYPE_CHECKING
import pyspark
from pyspark.errors.error_classes import ERROR_CLASSES_MAP

if TYPE_CHECKING:
Expand Down Expand Up @@ -164,9 +165,29 @@ def _capture_call_site(spark_session: "SparkSession", depth: int) -> str:
The call site information is used to enhance error messages with the exact location
in the user code that led to the error.
"""
stack = list(reversed(inspect.stack()))
# Filtering out PySpark code and keeping user code only
pyspark_root = os.path.dirname(pyspark.__file__)
stack = [
frame_info for frame_info in inspect.stack() if pyspark_root not in frame_info.filename
]

selected_frames = stack[:depth]
call_sites = [f"{frame.filename}:{frame.lineno}" for frame in selected_frames]

# We try import here since IPython is not a required dependency
try:
from IPython import get_ipython

ipython = get_ipython()
except ImportError:
ipython = None

# Identifying the cell is useful when the error is generated from IPython Notebook
if ipython:
call_sites = [
f"line {frame.lineno} in cell [{ipython.execution_count}]" for frame in selected_frames
]
else:
call_sites = [f"{frame.filename}:{frame.lineno}" for frame in selected_frames]
call_sites_str = "\n".join(call_sites)

return call_sites_str
Expand Down