Imam al-Shafi'i (may Allah have mercy on him) said: "The Messenger of Allah (peace and blessings be upon him) carried out the prescribed punishment (hadd) in Madinah, although shirk (that is, the polytheists) was close to it, and in Madinah itself there were many polytheists with whom there was a peace treaty; and he (peace and blessings be upon him) had the drinker (of wine) beaten (as the hadd) at Hunayn, while shirk (the polytheists) was close to him."
Hadith Referenceالسنن الكبرى للبيهقي / كتاب السير / Q18217