Jump to content
iqrf

PyDict - how to set readonly

Recommended Posts

Hello,
I have such a dictionary

...  AddMethod( 'TestArray', @TPyPoint.DoTestArray, 'Point.TestArray()' );

function TPyPoint.DoTestArray(args : PPyObject): PPyObject; cdecl;
type
  TDevice = record
    ValueA: Integer;
    ValueB: String;
  end;

  TDevices = array of TDevice;

var
  DeviceArray: TDevices;
  I: Integer;
  DeviceList: PPyObject;
  DeviceDict: PPyObject;

function TDeviceToPyObject(const Device: TDevice): PPyObject;
var
  DeviceDict: PPyObject;
begin
  with GetPythonEngine do begin
    DeviceDict := PyDict_New;

    PyDict_SetItemString(DeviceDict, 'ValueA', PyLong_FromLong(Device.ValueA));
    PyDict_SetItemString(DeviceDict, 'ValueB', PyUnicodeFromString(PAnsiChar(AnsiString(Device.ValueB))));

    Result := DeviceDict;
  end;
end;

begin
  SetLength(DeviceArray, 2);
  DeviceArray[0].ValueA := 1;
  DeviceArray[0].ValueB := 'Device 1';
  DeviceArray[1].ValueA := 2;
  DeviceArray[1].ValueB := 'Device 2';

  with GetPythonEngine do begin
    Adjust(@Self);
    
    DeviceList := PyList_New(0);

    for I := 0 to High(DeviceArray) do begin
      DeviceDict := TDeviceToPyObject(DeviceArray[I]);
      PyList_Append(DeviceList, DeviceDict);
      Py_DecRef(DeviceDict);
    end;

    Result := DeviceList;
  end;
end;

Is there any possibility to make the data read-only in Python?

I can only do this if I pass them as Tuples using ArrayToPyTuple(MyArray), but then it's just a one-dimensional array.

And one more question, how to pass TDevice data to Python so that it can be written in Python

instead of this one

a = spam.myPoint.TestArray()
print(a[0]['ValueA'])
print(a[0]['ValueB'])

this one

a = spam.myPoint.TestArray()
print(a[0].ValueA)
print(a[0].ValueB)

Thanks.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×