Skip to content

Commit 28500d4

Browse files
author
Christopher Doris
committed
conversion to named tuple
1 parent 8b573c8 commit 28500d4

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

src/cpython/CPython.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,7 @@ __init__() = begin
189189
(Vector, PyIterable_ConvertRule_vecorset),
190190
(Set, PyIterable_ConvertRule_vecorset),
191191
(Tuple, PyIterable_ConvertRule_tuple),
192+
(NamedTuple, PyIterable_ConvertRule_namedtuple),
192193
(Pair, PyIterable_ConvertRule_pair),
193194
],
194195
)

src/cpython/collections.jl

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -156,13 +156,7 @@ PyIterable_ConvertRule_vecorset(o, ::Type{Set}) =
156156
PyIterable_ConvertRule_vecorset(o, Set{Python.PyObject})
157157

158158
PyIterable_ConvertRule_tuple(o, ::Type{S}) where {S<:Tuple} = begin
159-
if !(S isa DataType)
160-
PyErr_SetString(
161-
PyExc_Exception(),
162-
"When converting Python 'tuple' to Julia 'Tuple', the destination type must be a 'DataType', i.e. not parametric and not a union. Got '$S'.",
163-
)
164-
return -1
165-
end
159+
S isa DataType || return 0
166160
ts = S.parameters
167161
if !isempty(ts) && Base.isvarargtype(ts[end])
168162
isvararg = true
@@ -190,6 +184,17 @@ PyIterable_ConvertRule_tuple(o, ::Type{S}) where {S<:Tuple} = begin
190184
r == -1 ? -1 : r == 0 ? 0 : length(xs) length(ts) ? putresult(S(xs)) : 0
191185
end
192186

187+
PyIterable_ConvertRule_namedtuple(o, ::Type{NamedTuple{names, types}}) where {names, types<:Tuple} = begin
188+
r = PyIterable_ConvertRule_tuple(o, types)
189+
r == 1 ? putresult(NamedTuple{names, types}(takeresult(types))) : r
190+
end
191+
PyIterable_ConvertRule_namedtuple(o, ::Type{NamedTuple{names}}) where {names} = begin
192+
types = NTuple{length(names), Python.PyObject}
193+
r = PyIterable_ConvertRule_tuple(o, types)
194+
r == 1 ? putresult(NamedTuple{names}(takeresult(types))) : r
195+
end
196+
PyIterable_ConvertRule_namedtuple(o, ::Type{S}) where {S<:NamedTuple} = 0
197+
193198
PyIterable_ConvertRule_pair(o, ::Type{Pair{K,V}}) where {K,V} = begin
194199
k = Ref{K}()
195200
v = Ref{V}()

0 commit comments

Comments
 (0)