How do I convert a python float to a Float32?

I am trying to iterated over a python list and compare the values to those in a Mojo Float32 list, but I have not found a way of converting a python float to any Mojo type for comparison.

I’ve tried Float32(f.to_float64()), but to_float64() returns a PythonObject and Float32 cannot convert a PythonObject. The same happens with Float64(f). Replacing the Float## with SIMD[DType.float##] also doesn’t work, and removing the to_float64() doesn’t work either.

Does anyone know what I am doing wrong or how I can fix this?

It’s gotta be here: Python types | Modular

PythonObject.to_float64() was deprecated in 25.3 (2025-05-06) and has since been removed. Could you try upgrading? This code should run:

from python import PythonObject

def main():
  o = PythonObject(1.0)
  _ = Float32(py=o)
  _ = Float64(py=o)

I have the same problem here on line 128 (currently commented out).

My solution in line 129 is uhhhh, not good.

There are some spots in the codebase where Float64(py=py_val) works fine and some places where it doesn’t. What am I not understanding?

Thanks,

Sam

I was able to find a solution to this that might help someone else. I made a separate .mojo file with the following function in it:

fn py_to_float64(py_float: PythonObject) raises -> Float64:
    return Float64(py=py_float)

and I imported this file to the file where I needed the conversion to happen. Works great.

Sorry for the delay, I thought I already sent this. This solution works! I suppose the issue I was having before was that I wasn’t including PythonObject. It seems a strange requirement given that I had already been interacting with PythonObjects. I also had been using 26.0.2. Thanks!