This week's Torah portion - meanderings
Just before this chapter came the seeming digression of the Judah-Tamar story, although as many commentators argue, there is an implicit contrast set up here between Joseph's restraint in the face of temptation and Judah's lack of it. I would argue that there is also a practical safety angle here. A slave sleeping with his master's wife is far more likely to get into trouble than a respectable widower paying a prostitute, sacred or otherwise. Perhaps Joseph would not have been quite so virtuous in Judah's situation.
It's also pretty amazing that Joseph, a pampered seventeen-year-old suddenly seized by his own brothers and sold into slavery, should have enough aplomb and expertise to do so well, but then, like the children of Lake Woebegon, our biblical heroes, whatever their flaws, are all above average in ability. (Even Isaac, whom we generally consider to be a bit of a nonentity, reaps a hundredfold what he sows and hobnobs quite comfortably with kings and chieftains.)