The torah tells us that it is forbidden to kindle fire on Shabbat, and
the rabbis understand this to apply to extinguishing a flame as well.
A mishna at the end of today's daf teaches: If one extinguishes the lamp
because he is afraid of robbers, gentiles, or an evil spirit, or for the
sake of an invalid who wants to sleep, he is not culpable. But if he
does so because he wants to spare the lamp, the oil, or the wick, he is
culpable. R. Yose exempts him in all cases except the wick (because he
is making charcoal). (29b)
(The g'mara here does not expound on fear of gentiles or evil spirits.)