Search code examples
pythondelphiembedding

NaN giving an error depending on Python startup?


I am using Python4Delphi to embed Python in a Delphi program. Versions: Python 2.6.4, Delphi 2009, Windows XP.

The Delphi program crashes with EInvalidOp when importing json. I tracked it to the line

NaN, PosInf, NegInf = float('nan'), float('inf'), float('-inf')

in json.decoder.

Sure enough, the command float('nan') raises an EInvalidOp when run inside Python embedded in the Delphi program. When executed in the command line Python (same installation) it simply returns nan.

Any idea what is the difference between the Python standard startup and that of the embedded one that may result in such an error?


Solution

  • This is most likely that Python uses a different 8087 control word (CW) setting than Delphi.

    Try this kind of code:

    var
      OldControlWord: Word;
    begin
      OldControlWord := Get8087CW();
      Set8087CW($133F);
      try
        // perform your Python code here
      finally
        Set8087CW(OldControlWord);      
      end;
    end;
    

    See my blog article on the 8087 CW in Delphi for a more detailed explanation of the $133F value.
    It needs the JCL for the T8087Precision type (which is in the Jcl8087 unit).

    --jeroen