Skip to content

Allow decoders affect PyObject.As<object>() #1546

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
Sep 14, 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
25 changes: 25 additions & 0 deletions src/embed_tests/Codecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,31 @@ from datetime import datetime

public static void AcceptsDateTime(DateTime v) {}

[Test]
public void As_Object_AffectedByDecoders()
{
var everythingElseToSelf = new EverythingElseToSelfDecoder();
PyObjectConversions.RegisterDecoder(everythingElseToSelf);

var pyObj = PythonEngine.Eval("iter");
var decoded = pyObj.As<object>();
Assert.AreSame(everythingElseToSelf, decoded);
}

public class EverythingElseToSelfDecoder : IPyObjectDecoder
{
public bool CanDecode(PyObject objectType, Type targetType)
{
return targetType.IsAssignableFrom(typeof(EverythingElseToSelfDecoder));
}

public bool TryDecode<T>(PyObject pyObj, out T value)
{
value = (T)(object)this;
return true;
}
}

class ValueErrorWrapper : Exception
{
public ValueErrorWrapper(string message) : base(message) { }
Expand Down
14 changes: 2 additions & 12 deletions src/runtime/pyobject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,20 +163,10 @@ public object AsManagedObject(Type t)
}

/// <summary>
/// As Method
/// </summary>
/// <remarks>
/// Return a managed object of the given type, based on the
/// value of the Python object.
/// </remarks>
public T As<T>()
{
if (typeof(T) == typeof(PyObject) || typeof(T) == typeof(object))
{
return (T)(this as object);
}
return (T)AsManagedObject(typeof(T));
}
/// </summary>
public T As<T>() => (T)this.AsManagedObject(typeof(T));

internal bool IsDisposed => obj == IntPtr.Zero;

Expand Down