diff --git a/src/runtime/pyiterable.cs b/src/runtime/pyiterable.cs index 47e6984d7..735bb86ab 100644 --- a/src/runtime/pyiterable.cs +++ b/src/runtime/pyiterable.cs @@ -13,6 +13,18 @@ internal PyIterable(IntPtr ptr) : base(ptr) internal PyIterable(BorrowedReference reference) : base(reference) { } internal PyIterable(in StolenReference reference) : base(reference) { } + /// + /// Creates new instance from an existing object. + /// + /// This constructor does not check if is actually iterable. + public PyIterable(PyObject o) : base(FromObject(o)) { } + + static BorrowedReference FromObject(PyObject o) + { + if (o is null) throw new ArgumentNullException(nameof(o)); + return o.Reference; + } + /// /// Return a new PyIter object for the object. This allows any iterable /// python object to be iterated over in C#. A PythonException will be diff --git a/src/runtime/pysequence.cs b/src/runtime/pysequence.cs index b112d6cb2..d42db9566 100644 --- a/src/runtime/pysequence.cs +++ b/src/runtime/pysequence.cs @@ -1,3 +1,4 @@ +#nullable enable using System; namespace Python.Runtime @@ -14,6 +15,18 @@ public class PySequence : PyIterable internal PySequence(BorrowedReference reference) : base(reference) { } internal PySequence(in StolenReference reference) : base(reference) { } + /// + /// Creates new instance from an existing object. + /// + /// does not provide sequence protocol + 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; + } /// /// Returns true if the given object implements the sequence protocol.