# Rank function for a projective module is locally constant

Let $M$ be a finitely generated projective module over a ring $R$, and let $X = \operatorname{Spec}R$. For each prime $\mathfrak p$ of $R$, $M_{\mathfrak p}$ is a finite rank free $R_{\mathfrak p}$-module, because projective modules over local rings are free. Define the rank function $r: |X| \rightarrow \mathbf N \cup \{0\}$ by $r(\mathfrak p) = \operatorname{Rank}_{R_{\mathfrak p}} M_{\mathfrak p}$. I am trying to understand why this function is locally constant.

If I consider neighborhoods $D(f)$ of $\mathfrak p$ (for $f \in R, \not\in \mathfrak p$), it would be enough to show that for $D(f)$ sufficiently small, $M_f$ is a free $A_f$-module. I don't know whether this is too much to hope for.

This is correct certainly for Noetherian rings. If $M_P$ is free, you can find a free module and a map $R^n\to M$ such that it is an isomorphism when you localize at $P$. Both kernel and cokernel are finitely generated and when localize at $P$, they are zero so you can find an $f\not\in P$ such that when you localize at $f$, both are zero.