robshakir / pyangbind

A plugin for pyang that creates Python bindings for a YANG model.
Other
203 stars 121 forks source link

Process for moving a list element #333

Closed ianbarrere closed 9 months ago

ianbarrere commented 9 months ago

First of all, fantastic tool. This will help me a lot in my current project.

I'm wondering what the general process for moving a list element is though. The use case is for things that are processed in their given order on a platform, like route-maps on a Cisco device, for example. I am working on a tool for interacting with them, and need a way to take a statement from /routing-policy/policy-definitions/policy-definition/statements/statement and put it elsewhere in the same list. I.e. take statement 10 and move it to statement 20 so I can insert a new statement 10.

I haven't tried, but I could surely serialize the thing, edit the key, then deserialize it, but I'm wondering if there's a more straightforward way. I see also that if I attempt to change key directly I hit this error:

rp.binding.policy_definitions.policy_definition['MY_POLICY'].statements.statement[10].name = 20 ... raise AttributeError("Cannot set keys directly when" + AttributeError: Cannot set keys directly when within an instantiated list

It appears there's not a method dedicated to moving list elements as such, so I'm aware that any solution will require a few steps, but that's fine, just trying to figure out the process.

xavier-contreras commented 9 months ago

I don't think there's an easy answer here -- maybe avoid doing this altogether and just create the structure in the right order.

The base element is an ordered dict, and there is no built in way to move a k/v to a specific position or "insert before/after". The functions available for YANG List are here: https://github.com/robshakir/pyangbind/blob/master/docs/generic_methods.md#yang-list-methods-

ianbarrere commented 9 months ago

Thanks for the response, I think you're right. I sort of came to that conclusion after posting this as well. What I generally strive to achieve in route-maps on Cisco devices, for example, is having each statement increment by 10, but that's more compulsive on my part than anything functional. What I was doing before using pyangbind was building a list of the statements and then when building the JSON body just multiplying the list index by 10 for the statement number.

Anyway, I'll try to resist the urge and use the gaps between the statements for their intended purpose if I need to insert something there later. And I suppose there is always the option of serializing, reordering, and deserializing.