Skip to content

Commit 598252b

Browse files
authored
add float(::PyObject) (#660)
* add float(::PyObject) * check for __float__ method as a fallback * whoops
1 parent 7f37853 commit 598252b

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/conversions.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,15 @@ convert(::Type{T}, po::PyObject) where T<:Complex =
6363

6464
convert(::Type{Nothing}, po::PyObject) = nothing
6565

66+
function Base.float(o::PyObject)
67+
a = PyAny(o)
68+
if a isa PyObject
69+
hasproperty(o, :__float__) && return o.__float__()
70+
throw(ArgumentError("don't know how convert $o to a Julia floating-point value"))
71+
end
72+
return float(a)
73+
end
74+
6675
#########################################################################
6776
# String conversions (both bytes arrays and unicode strings)
6877

test/runtests.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ pymodule_exists(s::AbstractString) = !ispynull(pyimport_e(s))
2626
# default integer type for PyAny conversions
2727
const PyInt = pyversion < v"3" ? Int : Clonglong
2828

29-
@testset "PyCall" begin
29+
@testset "conversions" begin
3030
# conversion of NumPy scalars before npy_initialized by array conversions (#481)
3131
np = pyimport_e("numpy")
3232
if !ispynull(np) # numpy is installed, so test
@@ -569,6 +569,11 @@ const PyInt = pyversion < v"3" ? Int : Clonglong
569569

570570
# issue #533
571571
@test py"lambda x,y,z: (x,y,z)"(3:6,4:10,5:11) === (PyInt(3):PyInt(6), PyInt(4):PyInt(10), PyInt(5):PyInt(11))
572+
573+
@test float(PyObject(1)) === 1.0
574+
@test float(PyObject(1+2im)) === 1.0 + 2.0im
575+
@test float(PyObject([1,2,3]))[2] === 2.0
576+
@test_throws ArgumentError float(pybuiltin("type"))
572577
end
573578

574579
######################################################################

0 commit comments

Comments
 (0)