Safer `GetAttr(name, default)` by lostmsu · Pull Request #1578 · pythonnet/pythonnet · GitHub
Skip to content
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions CHANGELOG.md
21 changes: 21 additions & 0 deletions src/embed_tests/TestPyObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,26 @@ public void UnaryMinus_ThrowsOnBadType()
var error = Assert.Throws<PythonException>(() => list = -list);
Assert.AreEqual("TypeError", error.Type.Name);
}

[Test]
[Obsolete]
public void GetAttrDefault_IgnoresAttributeErrorOnly()
{
var ob = new PyObjectTestMethods().ToPython();
using var fallback = new PyList();
var attrErrResult = ob.GetAttr(nameof(PyObjectTestMethods.RaisesAttributeError), fallback);
Assert.IsTrue(PythonReferenceComparer.Instance.Equals(fallback, attrErrResult));

var typeErrResult = Assert.Throws<PythonException>(
() => ob.GetAttr(nameof(PyObjectTestMethods.RaisesTypeError), fallback)
);
Assert.AreEqual(Exceptions.TypeError, typeErrResult.Type.Handle);
}
}

public class PyObjectTestMethods
{
public string RaisesAttributeError => throw new PythonException(new PyType(new BorrowedReference(Exceptions.AttributeError)), value: null, traceback: null);
public string RaisesTypeError => throw new PythonException(new PyType(new BorrowedReference(Exceptions.TypeError)), value: null, traceback: null);
}
}
51 changes: 40 additions & 11 deletions src/runtime/pyobject.cs