It was Jesus getting himself out of a sticky situation with the OT on one side and the Romans on the other. They were trying to entrap him because the Romans had sole authority to execute/kill.
Agreed, but Jesus often did more than one thing at a time, so even if it can be proved to be one thing, it doesn't necessarily mean it isn't something else as well.
In Leviticus 20:10 we read
"And the man that committeth adultery with another man's wife, even he that committeth adultery with his neighbour's wife, the adulterer and the adulteress shall surely be put to death."
So why did they only bring the woman? Where was the man?
Agreed, it sounds like the whole thing could have been a staged trap, but I don't think we can be dogmatic either way.
On the other hand, there are some textual critics that claim this was an extra biblical account woven in years after the book was written.
I think an important approach to textual criticism is whether the disputed text is in accordance with other scriptures or not. I don't think any translation is 100% accurate, but if we believe that if God inspired scripture in the first place it is reasonable to believe that he would also oversee the scriptures we have now to the point that we have sufficient witness to sort it out.
So - is what this passage teaches in accordance with other scriptures or not?
1) In modern parlance, the NT Jews were a trigger-happy lot. Jesus countered this with compassion and expected it in others, e.g. healing on the sabbath. This passage agrees with the compassion we see taught elsewhere.
2) Yes the law would have dealt with the problem by stoning. There was no forgiveness under the law for David's sin with Bathsheba but he obtained grace. Jesus used his power to convince the witnesses that they were in the wrong place, and they went away. No witnesses, no conviction, and so grace was also extended to this woman.
3) Joseph would not have been the guardian of Jesus if he had tried to apply the full force of the law to Mary's pregnancy.
The record of this incident is then simply one more instance of the teaching that the strictness of the law in enforcing the death penalty should be postponed (we all still die anyway). Postponement provides an opportunity to respond to Christ's teaching "Go and sin no more".
God "is longsuffering to us-ward, not willing that any should perish, but that all should come to repentance." 2Pe 3:9