pybind / pybind/pybind11

[BUG] Raising exception from runtime context

Open
#2,973 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Hi,
I've encounter the issue with exception and context manager.
Given this file:

import contextlib

@contextlib.contextmanager
def test_ctx(Arg):
	try:
		yield Arg
	finally:
		pass

def func():
	a = 5
	print('ssss')
	with test_ctx(''):  # (1)
#	if True:
		raise Exception()
		print('aaa')
		print('aaa')
		print('aaa')
		print('aaa')    # (2)
	
func()

When I run it from python.exe, I've got:

  File "file.py", line 21, in <module>
    func()
  File "file.py", line 15, in func
    raise Exception()
Exception

But when I run it with pybind11::exec() I've got:


At:
  d:\temp\delete\TRASH\py_att\runtime\file.py(19): func
  d:\temp\delete\TRASH\py_att\runtime\file.py(21): <module>
  <frozen importlib._bootstrap>(219): _call_with_frames_removed
  <frozen importlib._bootstrap_external>(678): exec_module
  <frozen importlib._bootstrap>(665): _load_unlocked
  <frozen importlib._bootstrap>(955): _find_and_load_unlocked
  <frozen importlib._bootstrap>(971): _find_and_load
  <string>(2): <module>

Now as you can see, the python.exe reports the line number where the exception was raise correctly 15 (1) . While pybind11 report it incorrectly 19 (2) when context manager is destroyed. It's really anoying because if you have lot of code in "with" then you cannot figure out where exactly does Exception originated from.
If the with is removed, everything works ok in pybind11.

Is this a bug or what?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the provided file.py through pybind11::exec and compare its traceback with direct execution via python.exe. Start at the pybind11::exec entry point and investigate why the context manager reports the later line instead of the raise line; done when the embedded execution identifies the exception's originating line correctly.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.