You can switch between uid's using os.seteuid(). This differs from os.setuid() in that you can go back to getting root privileges when you need them.
For example, run the following as root:
import os
open('file1', 'wc')
# switch to userid 501
os.seteuid(501)
open('file2', 'wc')
# switch back to root
os.seteuid(0)
open('file3', 'wc')
This creates file1 and file3 as root, but file2 as the user with uid 501.
If you want to determine which user is calling your script, sudo sets two environment variables:
SUDO_USER
SUDO_UID
Respectively the username and the uid of the user who called sudo. So you could use int(os.environ['SUDO_UID']) to use with os.seteuid().