Let's assume there is a point layer called 'points_test' with its attribute table, see image below.

As you can see there are two fields in it:
Name:id | TypeName:Integer | Type:2 | Length:1
Name:TEST | TypeName:String | Type:10 | Length:10
By default my values in the attribute table are sorted by "id"
fields. How one can know that?
Open Attribute Table (F6) and proceed with Right Mouse Click on the column header > Sort...

Now, I will configure attribute table sort order and switch to another field. In the pop-up window insert the desired field, in my case it is "TEST"
, instead of "id"
.

And now as you can see that my attribute table was visually changed into different sorting order evoked from the "TEST"
field.

The same action can be performed with PyQGIS.
Proceed with Plugins > Python Console > Show Editor
and paste the script below
layer = iface.activeLayer()
config = layer.attributeTableConfig()
config.setSortExpression("TEST") # name of the field
config.setSortOrder(0) # 0:ascending 1:descending
layer.setAttributeTableConfig(config)
iface.showAttributeTable(layer)
Press Run script
and get the output the same as was achieved above.
References: