Skip to content
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
allow user-created instances of PySequence and PyIterable
  • Loading branch information
lostmsu committed Oct 1, 2021
commit c09de96a79d7274bbc89148ede35d94ce5eb07d8
12 changes: 12 additions & 0 deletions src/runtime/pyiterable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ internal PyIterable(IntPtr ptr) : base(ptr)
internal PyIterable(BorrowedReference reference) : base(reference) { }
internal PyIterable(in StolenReference reference) : base(reference) { }

/// <summary>
/// Creates new instance from an existing object.
/// </summary>
/// <remarks>This constructor does not check if <paramref name="o"/> is actually iterable.</remarks>
public PyIterable(PyObject o) : base(FromObject(o)) { }

static BorrowedReference FromObject(PyObject o)
{
if (o is null) throw new ArgumentNullException(nameof(o));
return o.Reference;
}

/// <summary>
/// Return a new PyIter object for the object. This allows any iterable
/// python object to be iterated over in C#. A PythonException will be
Expand Down
13 changes: 13 additions & 0 deletions src/runtime/pysequence.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#nullable enable
using System;

namespace Python.Runtime
Expand All @@ -14,6 +15,18 @@ public class PySequence : PyIterable
internal PySequence(BorrowedReference reference) : base(reference) { }
internal PySequence(in StolenReference reference) : base(reference) { }

/// <summary>
/// Creates new instance from an existing object.
/// </summary>
/// <exception cref="ArgumentException"><paramref name="o"/> does not provide sequence protocol</exception>
public PySequence(PyObject o) : base(FromObject(o)) { }

static BorrowedReference FromObject(PyObject o)
{
if (o is null) throw new ArgumentNullException(nameof(o));
if (!IsSequenceType(o)) throw new ArgumentException("object is not a sequence");
return o.Reference;
}

/// <summary>
/// Returns <c>true</c> if the given object implements the sequence protocol.
Expand Down