Use safe_hasattr in dir2

Add test cases

Move safe_hasattr to utils/dir2
Merge pull request #4382 from jtratner/safer-hasattr-in-dir2

Use safe_hasattr in dir2