Skip to content

Some fixes. #219

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jul 28, 2016
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
2 changes: 1 addition & 1 deletion src/runtime/classderived.cs
Original file line number Diff line number Diff line change
Expand Up @@ -786,7 +786,7 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, Objec
PyObject[] pyargs = new PyObject[args.Length];
for (int i = 0; i < args.Length; ++i)
{
pyargs[i] = new PyObject(Converter.ToPython(args[i], args[i].GetType()));
pyargs[i] = new PyObject(Converter.ToPython(args[i], args[i]?.GetType()));
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we are not ready for C# 6+ only support. Please do not use "Null-conditional operators" in C# 4.0 codebase.

disposeList.Add(pyargs[i]);
}

Expand Down
4 changes: 2 additions & 2 deletions src/runtime/converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ internal static IntPtr ToPython(Object value, Type type)
{
foreach (object o in (IEnumerable)value)
{
using (var p = new PyObject(ToPython(o, o.GetType())))
using (var p = new PyObject(ToPython(o, o?.GetType())))
resultlist.Append(p);
}
Runtime.Incref(resultlist.Handle);
Expand Down Expand Up @@ -962,7 +962,7 @@ public static class ConverterExtension
{
public static PyObject ToPython(this object o)
{
return new PyObject(Converter.ToPython(o, o.GetType()));
return new PyObject(Converter.ToPython(o, o?.GetType()));
}
}
}
5 changes: 4 additions & 1 deletion src/runtime/moduleobject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ public ModuleObject(string name) : base()
string docstring = "Namespace containing types from the following assemblies:\n\n";
foreach (Assembly a in AssemblyManager.GetAssemblies(name))
{
filename = a.Location;
if (!a.IsDynamic && a.Location != null)
{
filename = a.Location;
}
docstring += "- " + a.FullName + "\n";
}

Expand Down
27 changes: 21 additions & 6 deletions src/runtime/pyobject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -939,7 +939,7 @@ public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (this.HasAttr(binder.Name))
{
result = this.GetAttr(binder.Name);
result = CheckNone(this.GetAttr(binder.Name));
return true;
}
else
Expand Down Expand Up @@ -972,7 +972,7 @@ private void GetArgs(object[] inargs, out PyTuple args, out PyDict kwargs)
}
else
{
ptr = Converter.ToPython(inargs[i], inargs[i].GetType());
ptr = Converter.ToPython(inargs[i], inargs[i]?.GetType());
}
if (Runtime.PyTuple_SetItem(argtuple, i, ptr) < 0)
throw new PythonException();
Expand All @@ -999,7 +999,7 @@ public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, o
try
{
GetArgs(args, out pyargs, out kwargs);
result = InvokeMethod(binder.Name, pyargs, kwargs);
result = CheckNone(InvokeMethod(binder.Name, pyargs, kwargs));
}
finally
{
Expand All @@ -1023,7 +1023,7 @@ public override bool TryInvoke(InvokeBinder binder, object[] args, out object re
try
{
GetArgs(args, out pyargs, out kwargs);
result = Invoke(pyargs, kwargs);
result = CheckNone(Invoke(pyargs, kwargs));
}
finally
{
Expand Down Expand Up @@ -1133,10 +1133,25 @@ public override bool TryBinaryOperation(BinaryOperationBinder binder, Object arg
result = null;
return false;
}
result = new PyObject(res);
result = CheckNone(new PyObject(res));
return true;
}

// Workaround for https://bugzilla.xamarin.com/show_bug.cgi?id=41509
// See https://github.com/pythonnet/pythonnet/pull/219
private static object CheckNone(PyObject pyObj)
{
if (pyObj != null)
{
if (pyObj.obj == Runtime.PyNone)
Copy link
Contributor

Choose a reason for hiding this comment

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

Doesn't this alter the behaviour? Previously a PyObject wrapping None would be returned, but now that's replaced with null? I must be missing something...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah you are right, it is a workaround that you are not able to return null via dynamic conversion (=later) on mono. please see the linked bug report as well. Feel free to ask if you want a code example (could take some time though)

Copy link
Contributor

@tonyroberts tonyroberts Jun 23, 2016

Choose a reason for hiding this comment

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

Yeah I get that, but here you are returning null where previously an object (PyNone) was returned. Could function just not return pyObj without checking for None? That's the bit I don't understand.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

you could and even should imho, but then you are triggering the mono bug :). The problem is later. when you save such a none object in a dynamic and want to resolve it to a string (for example). This will not work as long as the mono bug exists. In fact one of my tests discovered this glitch

Copy link
Contributor

Choose a reason for hiding this comment

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

Ah ok, that was the bit I was missing - that the bug was triggered later when dealing with the None PyObject instance.

{
return null;
}
}

return pyObj;
}

public override bool TryUnaryOperation(UnaryOperationBinder binder, out Object result)
{
int r;
Expand Down Expand Up @@ -1170,7 +1185,7 @@ public override bool TryUnaryOperation(UnaryOperationBinder binder, out Object r
result = null;
return false;
}
result = new PyObject(res);
result = CheckNone(new PyObject(res));
return true;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/pythonengine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ public static KeywordArguments kw(params object[] kv)
if (kv[i + 1] is PyObject)
value = ((PyObject)kv[i + 1]).Handle;
else
value = Converter.ToPython(kv[i + 1], kv[i + 1].GetType());
value = Converter.ToPython(kv[i + 1], kv[i + 1]?.GetType());
if (Runtime.PyDict_SetItemString(dict.Handle, (string)kv[i], value) != 0)
throw new ArgumentException(string.Format("Cannot add key '{0}' to dictionary.", (string)kv[i]));
if (!(kv[i + 1] is PyObject))
Expand Down
2 changes: 2 additions & 0 deletions src/testing/Python.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
</PropertyGroup>
<ItemGroup>
<Compile Include="arraytest.cs" />
<Compile Include="callbacktest.cs" />
<Compile Include="classtest.cs" />
<Compile Include="constructortests.cs" />
<Compile Include="conversiontest.cs" />
Expand All @@ -127,6 +128,7 @@
<Compile Include="subclasstest.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
Expand Down
31 changes: 31 additions & 0 deletions src/testing/callbacktest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Python.Test
{
//========================================================================
// Tests callbacks into python code.
//========================================================================

public class CallbackTest
{
public string Call_simpleDefaultArg_WithNull(string moduleName)
{
using (Runtime.Py.GIL())
{
dynamic module = Runtime.Py.Import(moduleName);
return module.simpleDefaultArg(null);
}
}
public string Call_simpleDefaultArg_WithEmptyArgs(string moduleName)
{
using (Runtime.Py.GIL())
{
dynamic module = Runtime.Py.Import(moduleName);
return module.simpleDefaultArg();
}
}
}
}
1 change: 1 addition & 0 deletions src/tests/runtests.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
# other test modules that import System.Windows.Forms
# run first. They must not do module level import/AddReference()
# of the System.Windows.Forms namespace.
'test_suite',
'test_event',
'test_constructors',
'test_enum',
Expand Down
12 changes: 12 additions & 0 deletions src/tests/test_suite/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import unittest

__all__ = ['test_suite']

from .test_import import test_suite as import_tests
from .test_callback import test_suite as callback_tests

def test_suite():
suite = unittest.TestSuite()
suite.addTests((import_tests(),))
suite.addTests((callback_tests(),))
return suite
2 changes: 2 additions & 0 deletions src/tests/test_suite/_missing_import.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

import this_package_should_never_exist_ever
30 changes: 30 additions & 0 deletions src/tests/test_suite/test_callback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import unittest, sys
import clr

this_module = sys.modules[__name__]
clr.AddReference("Python.Test")
import Python.Test as Test
from Python.Test import CallbackTest
test_instance = CallbackTest()

def simpleDefaultArg(arg = 'test'):
return arg

class CallbackTests(unittest.TestCase):
"""Test that callbacks from C# into python work."""

def testDefaultForNull(self):
"""Test that C# can use null for an optional python argument"""
retVal = test_instance.Call_simpleDefaultArg_WithNull(__name__)
pythonRetVal = simpleDefaultArg(None)
self.assertEquals(retVal, pythonRetVal)

def testDefaultForNone(self):
"""Test that C# can use no argument for an optional python argument"""
retVal = test_instance.Call_simpleDefaultArg_WithEmptyArgs(__name__)
pythonRetVal = simpleDefaultArg()
self.assertEquals(retVal, pythonRetVal)

def test_suite():
return unittest.makeSuite(CallbackTests)

16 changes: 16 additions & 0 deletions src/tests/test_suite/test_import.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import unittest

class ImportTests(unittest.TestCase):
"""Test the import statement."""

def testRealtiveMissingImport(self):
"""Test that a relative missing import doesn't crash. Some modules use this to check if a package is installed (realtive import in the site-packages folder"""
try:
from . import _missing_import
except ImportError:
pass


def test_suite():
return unittest.makeSuite(ImportTests)