Sometimes there are peculiarities in the use of key signatures.
Just one example is Edward MacDowell.
In one of his compositions, he writes in the key of 4 sharps, but he naturals out every sharp that appears in the first two lines of the score.
In another piece, he writes in the key of one flat, but naturals out all the flats in about the first page of the score.
Commonly, composers change keys as a piece progresses. They will then change the key signature for the intermezzo section. Chopin, for example.
Other composers seem to avoid changing the nominal signature, but will in effect change the key through a liberal use of accidentals. This makes for more difficulty in reading, and a cluttered score, so one wishes they would just mark a change of key.
Debussy in some pieces uses a frightfully large number of accidentals. Likewise, MacDowell, although a very different composer indeed, will also at times use an extraordinary number of accidentals. What can be maddening (to me, at least) about Debussy is that he will start in a very complex key for the reader, such as six flats, and then -- in addition -- scatter accidentals all over with reckless abandon. One wants to say, in the words of Lou Costello, "who's on first?"
My piano teacher, looking carefully at the extensive use of accidentals in MacDowell, will say of a long phrase, "in actuality, he is now in the key of _____." He just doesn't mark a change of key-- but does the job with abundant accidentals.
According to my piano teacher, most pieces will end in the signature key the piece is written in. So no matter how many accidentals or chord shifts occur within a particular piece, if you look at the final measure, you will usually see the signature key. It is as though the piece "comes home" in the final measure.
All this is interesting, but I am lame on theory so I only partly understand it.