Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Added python "with" construction
  • Loading branch information
dsuarezv committed May 6, 2017
commit 73c40fc6d484acaed68514955963a5512d086739
88 changes: 88 additions & 0 deletions src/embed_tests/TestPyWith.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using System;
using NUnit.Framework;
using Python.Runtime;

namespace Python.EmbeddingTest
{
public class TestPyWith
{
[OneTimeSetUp]
public void SetUp()
{
PythonEngine.Initialize();
}

[OneTimeTearDown]
public void Dispose()
{
PythonEngine.Shutdown();
}

/// <summary>
/// Test that exception is raised in context manager that ignores it.
/// </summary>
[Test]
public void TestPositiveWith()
{
var locals = new PyDict();

PythonEngine.Exec(@"
class cmTest:
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CmTest.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@filmor what do you mean here?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python convention for classes is CamelCase.

def __enter__(self):
print('Enter')
return self
def __exit__(self, t, v, tb):
# Exception not handled, return will be False
print('Exit')
def fail(self):
return 5 / 0

a = cmTest()
", null, locals.Handle);

var a = locals.GetItem("a");

try
{
Py.With(a, cmTest =>
{
cmTest.fail();
});
}
catch (PythonException e)
{
Assert.IsTrue(e.Message.Contains("division by zero"));
}
}


/// <summary>
/// Test that exception is not raised in context manager that handles it
/// </summary>
[Test]
public void TestNegativeWith()
{
var locals = new PyDict();

PythonEngine.Exec(@"
class cmTest:
def __enter__(self):
print('Enter')
return self
def __exit__(self, t, v, tb):
# Signal exception is handled by returning true
return True
def fail(self):
return 5 / 0

a = cmTest()
", null, locals.Handle);

var a = locals.GetItem("a");
Py.With(a, cmTest =>
{
cmTest.fail();
});
}
}
}
31 changes: 30 additions & 1 deletion src/runtime/pythonengine.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -632,5 +632,34 @@ public static void SetArgv(IEnumerable<string> argv)
Runtime.CheckExceptionOccurred();
}
}

public static void With(PyObject obj, Action<dynamic> Body)
{
// Behavior described here:
// https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers

IntPtr type = Runtime.PyNone;
IntPtr val = Runtime.PyNone;
IntPtr traceBack = Runtime.PyNone;
PythonException ex = null;

try
{
PyObject enterResult = obj.InvokeMethod("__enter__");

Body(enterResult);
}
catch (PythonException e)
{
ex = e;
type = ex.PyType;
val = ex.PyValue;
traceBack = ex.PyTB;
}

var exitResult = obj.InvokeMethod("__exit__", new PyObject(type), new PyObject(val), new PyObject(traceBack));

if (ex != null && !exitResult.IsTrue()) throw ex;
}
}
}