Skip to content

Commit ed594c1

Browse files
committed
cache PythonException message
1 parent 4877fe7 commit ed594c1

File tree

1 file changed

+10
-16
lines changed

1 file changed

+10
-16
lines changed

src/runtime/pythonexception.cs

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,19 @@ namespace Python.Runtime
1414
/// </summary>
1515
public class PythonException : System.Exception
1616
{
17-
1817
public PythonException(PyType type, PyObject? value, PyObject? traceback,
19-
Exception? innerException)
20-
: base("An exception has occurred in Python code. See Message property for details.", innerException)
18+
string message, Exception? innerException)
19+
: base(message, innerException)
2120
{
2221
Type = type ?? throw new ArgumentNullException(nameof(type));
2322
Value = value;
2423
Traceback = traceback;
2524
}
2625

26+
public PythonException(PyType type, PyObject? value, PyObject? traceback,
27+
Exception? innerException)
28+
: this(type, value, traceback, GetMessage(value, type), innerException) { }
29+
2730
public PythonException(PyType type, PyObject? value, PyObject? traceback)
2831
: this(type, value, traceback, innerException: null) { }
2932

@@ -178,7 +181,8 @@ private static Exception FromPyErr(BorrowedReference typeRef, BorrowedReference
178181

179182
private static string GetMessage(PyObject? value, PyType type)
180183
{
181-
using var _ = new Py.GILState();
184+
if (type is null) throw new ArgumentNullException(nameof(type));
185+
182186
if (value != null && !value.IsNone())
183187
{
184188
return value.ToString();
@@ -259,17 +263,6 @@ public override string StackTrace
259263
}
260264
}
261265

262-
public override string Message
263-
{
264-
get
265-
{
266-
if (!PythonEngine.IsInitialized && Runtime.Py_IsInitialized() == 0)
267-
return "Python error message is unavailable as runtime was shut down";
268-
269-
return GetMessage(this.Value, this.Type);
270-
}
271-
}
272-
273266
public bool IsNormalized
274267
{
275268
get
@@ -355,7 +348,8 @@ public string Format()
355348
}
356349

357350
public PythonException Clone()
358-
=> new PythonException(Type, Value, Traceback, InnerException);
351+
=> new PythonException(type: Type, value: Value, traceback: Traceback,
352+
Message, InnerException);
359353

360354
internal bool Is(IntPtr type)
361355
{

0 commit comments

Comments
 (0)