8000 fixed PyObject.As<object> returning PyObject · pythonnet/pythonnet@93e0bdb · GitHub
[go: up one dir, main page]

Skip to content

Commit 93e0bdb

Browse files
committed
fixed PyObject.As<object> returning PyObject
1 parent 2ef6b50 commit 93e0bdb

File tree

2 files changed

+27
-12
lines changed

2 files changed

+27
-12
lines changed

src/embed_tests/Codecs.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,31 @@ from datetime import datetime
373373

374374
public static void AcceptsDateTime(DateTime v) {}
375375

376+
[Test]
377+
public void As_Object_AffectedByDecoders()
378+
{
379+
var everythingElseToSelf = new EverythingElseToSelfDecoder();
380+
PyObjectConversions.RegisterDecoder(everythingElseToSelf);
381+
382+
var pyObj = PythonEngine.Eval("iter");
383+
var decoded = pyObj.As<object>();
384+
Assert.AreSame(everythingElseToSelf, decoded);
385+
}
386+
387+
public class EverythingElseToSelfDecoder : IPyObjectDecoder
388+
{
389+
public bool CanDecode(PyObject objectType, Type targetType)
390+
{
391+
return targetType.IsAssignableFrom(typeof(EverythingElseToSelfDecoder));
392+
}
393+
394+
public bool TryDecode<T>(PyObject pyObj, out T value)
395+
{
396+
value = (T)(object)this;
397+
return true;
398+
}
399+
}
400+
376401
class ValueErrorWrapper : Exception
377402
{
378403
public ValueErrorWrapper(string message) : base(message) { }

src/runtime/pyobject.cs

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -163,20 +163,10 @@ public object AsManagedObject(Type t)
163163
}
164164

165165
/// <summary>
166-
/// As Method
167-
/// </summary>
168-
/// <remarks>
169166
/// Return a managed object of the given type, based on the
170167
/// value of the Python object.
171-
/// </remarks>
172-
public T As<T>()
173-
{
174-
if (typeof(T) == typeof(PyObject) || typeof(T) == typeof(object))
175-
{
176-
return (T)(this as object);
177-
}
178-
return (T)AsManagedObject(typeof(T));
179-
}
168+
/// </summary>
169+
public T As<T>() => (T)this.AsManagedObject(typeof(T));
180170

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

0 commit comments

Comments
 (0)
0