Skip to content

Allow user-created instances of PySequence and PyIterable #1580

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 2, 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
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