We present a compact formula for the supersymmetric partition function of 2d N=(2,2), 3d N=2 and 4d N=1 gauge theories on $Sigma_g imes T^n$ with partial topological twist on $Sigma_g$, where $Sigma_g$ is a Riemann surface of arbitrary genus and $T^n$ is a torus with n=0,1,2, respectively. In 2d we also include certain local operator insertions, and in 3d we include Wilson line operator insertions along $S^1$. For genus g=1, the formula computes the Witten index. We present a few simple Abelian and non-Abelian examples, including new tests of non-perturbative dualities. We also show that the large N partition function of ABJM theory on $Sigma_g imes S^1$ reproduces the Bekenstein-Hawking entropy of BPS black holes in AdS$_4$ whose horizon has $Sigma_g$ topology.