Added encoding utf-8.
Replace type(...) is ... with isinstance.
Minor refactoring.
Using exception instead of hasattr.