8000 add a scope class to manage the context of interaction with Python an… · pythonnet/pythonnet@f413784 · GitHub
[go: up one dir, main page]

Skip to content

Commit f413784

Browse files
committed
add a scope class to manage the context of interaction with Python and simplify the variable exchanging
1 parent 1d583c7 commit f413784

File tree

3 files changed

+518
-0
lines changed

3 files changed

+518
-0
lines changed

src/embed_tests/Python.EmbeddingTest.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@
8484
<Compile Include="pyobject.cs" />
8585
<Compile Include="pythonexception.cs" />
8686
<Compile Include="pytuple.cs" />
87+
<Compile Include="pyscope.cs" />
8788
</ItemGroup>
8889
<ItemGroup>
8990
<ProjectReference Include="..\runtime\Python.Runtime.csproj">

src/embed_tests/pyscope.cs

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
using NUnit.Framework;
2+
using Python.Runtime;
3+
4+
namespace Python.EmbeddingTest
5+
{
6+
[TestFixture]
7+
public class PyScopeTest
8+
{
9+
PyScope ps;
10+
11+
public PyScopeTest()
12+
{
13+
ps = Py.Session("test");
14+
}
15+
16+
[SetUp]
17+
public void SetUp()
18+
{
19+
ps = Py.Session("test");
20+
}
21+
22+
[TearDown]
23+
public void TearDown()
24+
{
25+
ps.Dispose();
26+
}
27+
28+
/// <summary>
29+
/// Evaluation a Python expression and obtain the value.
30+
/// </summary>
31+
[Test]
32+
public void TestEval()
33+
{
34+
ps.SetLocal("a", 1);
35+
PyInt result = PyInt.AsInt(ps.Eval("a+2"));
36+
Assert.AreEqual(result.ToInt32(), 3);
37+
}
38+
39+
[Test]
40+
public void TestExec()
41+
{
42+
ps.SetGlobal("bb", 100); //declare a global variable
43+
ps.SetLocal("cc", 10); //declare a local variable
44+
ps.Exec("aa=bb+cc+3");
45+
int result = ps.Get<System.Int32>("aa");
46+
Assert.AreEqual(result, 113);
47+
}
48+
49+
[Test]
50+
public void TestSubScope()
51+
{
52+
ps.SetGlobal("bb", 100); //declare a global variable
53+
ps.SetLocal("cc", 10); //declare a local variable
54+
55+
PyScope scope = ps.SubScope();
56+
scope.Exec("aa=bb+cc+3");
57+
int result = scope.Get<System.Int32>("aa");
58+
Assert.AreEqual(result, 113); //
59+
scope.Dispose();
60+
61+
Assert.IsFalse(ps.Exists("aa"));
62+
}
63+
64+
[Test]
65+
public void TestImport()
66+
{
67+
ps.Import("sys");
68+
Assert.IsTrue(ps.Exists("sys"));
69+
}
70+
71+
[Test]
72+
public void TestImportAs()
73+
{
74+
ps.ImportAs("sys", "sys1");
75+
Assert.IsTrue(ps.Exists("sys1"));
76+
}
77+
78+
[Test]
79+
public void TestSuspend()
80+
{
81+
ps.SetGlobal("bb", 100);
82+
ps.SetLocal("cc", 10);
83+
ps.Suspend();
84+
using (Py.GIL())
85+
{
86+
PythonEngine.RunSimpleString("import sys;");
87+
}
88+
ps.Exec("aa=bb+cc+3");
89+
int result = ps.Get<System.Int32>("aa");
90+
Assert.AreEqual(result, 113);
91+
}
92+
}
93+
}

0 commit comments

Comments
 (0)
0