r/pythontips • • Oct 17 '21

Syntax Python Beginner Mistakes

As a Python trainer, I get to work with pynewbies across the spectrum. It doesn't matter whether they are from college or years into the industry when learning Python. The simplest language on the earth is not that intuitive. Things get even more challenging when they are well versed in a Typed-Object-Oriented-Language

I have compiled some of the common mistakes that beginners make.

https://thelearning.dev/python-beginner-mistakes

52 Upvotes

12 comments sorted by

View all comments

3

u/EyeofEnder Oct 18 '21

I've always used type() for built-in types and isinstance() for classes.

Is it better to just generally use isinstance() for type checking?

4

u/JRRudy Oct 18 '21

Yes, stick with isinstance() unless you have a specific reason not to. One key difference is that isinstance will allow subclasses. Say you have a function that takes in a dict as an argument. If you enforce the type using type() and the user inputs an object of a dict subclass such as OrderedDict, it will evaluate to False. This is rarely the desired behavior, as you should typically be able to do anything with an object of a subclass that you could do with an object of its superclass. Why restrict your function to specifically using a dict, when a subclass of dict will have all the methods and attributes it needs to play the part just as well?