fix nearly all undefined var errs reported by pyflakes

BTW, you guys might wanna integrate some Python lint tools (pylint, pyflakes) into your CI workflow to catch low-hanging fruit like this.