Use safe_hasattr in dir2

Add test cases

Move safe_hasattr to utils/dir2

Fixes #4381 (and helps out pydata/pandas#5182)