[SPARK-3679] [PySpark] pickle the exact globals of functions

function.func_code.co_names has all the names used in the function, including name of attributes. It will pickle some unnecessary globals if there is a global having the same name with attribute (in co_names).

There is a regression introduced by #2144, revert part of changes in that PR. 

cc @JoshRosen 
The original code only perform two levels of functions, the new version can handle multiple levels.

Each level is on function code, which is created by `def` or `lambda`, so I think the code cannot be recursive.