Skip to content

__name__ and __signature__ for .NET methods #1133

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 1 commit into from
Oct 1, 2021
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
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
- Ability to implement delegates with `ref` and `out` parameters in Python, by returning the modified parameter values in a tuple. ([#1355][i1355])
- `PyType` - a wrapper for Python type objects, that also permits creating new heap types from `TypeSpec`
- Improved exception handling:
- exceptions can now be converted with codecs
- `InnerException` and `__cause__` are propagated properly
* exceptions can now be converted with codecs
* `InnerException` and `__cause__` are propagated properly
- `__name__` and `__signature__` to reflected .NET methods
- .NET collection types now implement standard Python collection interfaces from `collections.abc`.
See [Mixins/collections.py](src/runtime/Mixins/collections.py).
- .NET arrays implement Python buffer protocol
Expand Down
25 changes: 25 additions & 0 deletions src/embed_tests/Inspect.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,30 @@ public void InstancePropertiesVisibleOnClass()
var pyProp = (PropertyObject)ManagedType.GetManagedObject(property.Reference);
Assert.AreEqual(nameof(Uri.AbsoluteUri), pyProp.info.Value.Name);
}

[Test]
public void BoundMethodsAreInspectable()
{
using var scope = Py.CreateScope();
try
{
scope.Import("inspect");
}
catch (PythonException)
{
Assert.Inconclusive("Python build does not include inspect module");
return;
}

var obj = new Class();
scope.Set(nameof(obj), obj);
using var spec = scope.Eval($"inspect.getfullargspec({nameof(obj)}.{nameof(Class.Method)})");
}

class Class
{
public void Method(int a, int b = 10) { }
public void Method(int a, object b) { }
}
}
}
1 change: 1 addition & 0 deletions src/runtime/exceptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,7 @@ public static variables on the Exceptions class filled in from
public static IntPtr IOError;
public static IntPtr OSError;
public static IntPtr ImportError;
public static IntPtr ModuleNotFoundError;
public static IntPtr IndexError;
public static IntPtr KeyError;
public static IntPtr KeyboardInterrupt;
Expand Down
71 changes: 71 additions & 0 deletions src/runtime/methodbinding.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Python.Runtime
Expand Down Expand Up @@ -65,6 +66,67 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx)
return mb.pyHandle;
}

PyObject Signature
{
get
{
var infos = this.info.Valid ? new[] { this.info.Value } : this.m.info;
Type type = infos.Select(i => i.DeclaringType)
.OrderByDescending(t => t, new TypeSpecificityComparer())
.First();
infos = infos.Where(info => info.DeclaringType == type).ToArray();
// this is a primitive version
// the overload with the maximum number of parameters should be used
MethodInfo primary = infos.OrderByDescending(i => i.GetParameters().Length).First();
var primaryParameters = primary.GetParameters();
PyObject signatureClass = Runtime.InspectModule.GetAttr("Signature");
var primaryReturn = primary.ReturnParameter;

using var parameters = new PyList();
using var parameterClass = primaryParameters.Length > 0 ? Runtime.InspectModule.GetAttr("Parameter") : null;
using var positionalOrKeyword = parameterClass?.GetAttr("POSITIONAL_OR_KEYWORD");
for (int i = 0; i < primaryParameters.Length; i++)
{
var parameter = primaryParameters[i];
var alternatives = infos.Select(info =>
{
ParameterInfo[] altParamters = info.GetParameters();
return i < altParamters.Length ? altParamters[i] : null;
}).Where(p => p != null);
using var defaultValue = alternatives
.Select(alternative => alternative.DefaultValue != DBNull.Value ? alternative.DefaultValue.ToPython() : null)
.FirstOrDefault(v => v != null) ?? parameterClass.GetAttr("empty");

if (alternatives.Any(alternative => alternative.Name != parameter.Name))
{
return signatureClass.Invoke();
}

using var args = new PyTuple(new[] { parameter.Name.ToPython(), positionalOrKeyword });
using var kw = new PyDict();
if (defaultValue is not null)
{
kw["default"] = defaultValue;
}
using var parameterInfo = parameterClass.Invoke(args: args, kw: kw);
parameters.Append(parameterInfo);
}

// TODO: add return annotation
return signatureClass.Invoke(parameters);
}
}

struct TypeSpecificityComparer : IComparer<Type>
{
public int Compare(Type a, Type b)
{
if (a == b) return 0;
if (a.IsSubclassOf(b)) return 1;
if (b.IsSubclassOf(a)) return -1;
throw new NotSupportedException();
}
}

/// <summary>
/// MethodBinding __getattribute__ implementation.
Expand All @@ -91,6 +153,15 @@ public static IntPtr tp_getattro(IntPtr ob, IntPtr key)
case "Overloads":
var om = new OverloadMapper(self.m, self.target);
return om.pyHandle;
case "__signature__" when Runtime.InspectModule is not null:
var sig = self.Signature;
if (sig is null)
{
return Runtime.PyObject_GenericGetAttr(ob, key);
}
return sig.NewReferenceOrNull().DangerousMoveToPointerOrNull();
case "__name__":
return self.m.GetName().DangerousMoveToPointerOrNull();
default:
return Runtime.PyObject_GenericGetAttr(ob, key);
}
Expand Down
12 changes: 11 additions & 1 deletion src/runtime/methodobject.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Reflection;

namespace Python.Runtime
{
Expand Down Expand Up @@ -101,6 +101,16 @@ internal IntPtr GetDocString()
return doc;
}

internal NewReference GetName()
{
var names = new HashSet<string>(binder.GetMethods().Select(m => m.Name));
if (names.Count != 1) {
Exceptions.SetError(Exceptions.AttributeError, "a method has no name");
return default;
}
return NewReference.DangerousFromPointer(Runtime.PyString_FromString(names.First()));
}


/// <summary>
/// This is a little tricky: a class can actually have a static method
Expand Down
3 changes: 3 additions & 0 deletions src/runtime/runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ internal static void Initialize(bool initSigs = false, ShutdownMode mode = Shutd
AssemblyManager.UpdatePath();

clrInterop = GetModuleLazy("clr.interop");
inspect = GetModuleLazy("inspect");
}

private static void InitPyMembers()
Expand Down Expand Up @@ -573,6 +574,8 @@ private static void MoveClrInstancesOnwershipToPython()
internal static IntPtr PyNone;
internal static IntPtr Error;

private static Lazy<PyObject> inspect;
internal static PyObject InspectModule => inspect.Value;
private static Lazy<PyObject> clrInterop;
internal static PyObject InteropModule => clrInterop.Value;

Expand Down