Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping track of data types in Python

Tags:

python

types

So I hope this is a valid question... I've recently (today actually) decided to learn how a scripting language, so I chose Python. While glancing over code, I felt overwhelmed, and I soon realized that the reason was that I didn't know what data type conversions and stuff were going on.

My question is: Is there any convention of keeping track of what the data type is? I come from more of a C background, so I find this quite confusing. Any tips?

like image 749
Dominic K Avatar asked Dec 05 '25 00:12

Dominic K


1 Answers

The normal Python approach is duck typing -- from the old phrase "if it quacks like a duck, and walks like a duck, it's duck enough for me".

In exceptional cases where you really must check what type something is (to do different things to otherwise similar types... usually not a good idea), that's what isinstance is for.

isinstance used to be considered a last-ditch measure, with serious warnings against overusing it... but while the gist of that classic tirade remains valid, since Python 2.6 it has acquired an important proviso: while checking if something is an instance of a specific concrete class remains in the "rarely a good idea" category, checking if it's an instance of an abstract base class (aka ABC) is a more frequently useful idea, because it just offers a nice and flexible way to check if something implements or not some interface.

For example, to check if an object is callable, one used to have to do something like:

if hasattr(type(obj), '__call__'): ...

Since 2.6, the preferred alternative has become:

import collections
if isinstance(obj, collections.Callable): ...

much more direct and cleaner. Richer ABCs such as, e.g., collections.MutableSequence, which imply the existence and coordination of many different methods, make this exponentially stronger.

The fact that checking (with isinstance) the membership in a concrete type is not so good, while checking the membership in an ABC is more often useful, lies in a principle that the "Gang of 4" expressed clearly and intensely in the first part of their wonderful book "Design Patterns" (in a mostly C++ context, but it really applies much more widely than that!): program to an interface, not to an implementation.

Checking membership of a concrete class indicates you're probably guilty of programming to an implementation; with an ABC, you're basically checking an interface, so many issues just aren't big problems any more (ABCs are more than just interfaces -- they can also offer "implementation help" to their concrete subclasses -- but, when we're talking about isinstance, thinking of them as interfaces is probably the most helpful stance).

like image 151
Alex Martelli Avatar answered Dec 07 '25 17:12

Alex Martelli