Mostly pylance type hinting fixes. Also contains minor code cleanup that should not have any functional change.