Explain Codes LogoExplain Codes Logo

How to determine a Python variable's type?

python
type-checking
variable-types
python-internals
Nikita BarsukovbyNikita Barsukov·Sep 19, 2024
TLDR

To quickly find out a variable's datatype in Python, use the inbuilt type() function, or to precisely ensure a variable is of a particular type, use the isinstance() function.

var = 123 print(type(var)) # <class 'int'>: Python saying "It's an integer, alright!" print(isinstance(var, int)) # True: Python affirming "Yes, indeed an integer!"

Let's delve into Python's toolbox

type() Function: the Type Tattler

With Python's type() function, we essentially interrogate our variable, asking politely, "Hey, var, what's your type?"

var = "Hello, World!" print(type(var)) # <class 'str': Python's fancy way to say "It's a string, dear programmer!"

isinstance() Function: the Type Truth Serum

To verify if a variable is of a specific type (or derived from it), isinstance() is our go-to truth serum.

print(isinstance(var, str)) # True: Python confirming "It's a string, you bet!"

Handling Types: The Chameleonic Approach

Dealing with shapesifters (data that can be of multiple types)? The isinstance() function plays nice with a tuple of types:

print(isinstance(var, (list, dict, str))) # True if `var` is a list, dict or string, else False. Python 1, Shapeshifters 0.

is Keyword: the Type Super Sleuth

The Python keyword is helps us perform a strict type check:

print(type(var) is int) # True if `var` is only an 'int', but False if it's merely masquerading as one (i.e., a subclass)

Peeling the Type Onion: Layers of Info

Get the Name Tag with __name__

Extract the type name as a handy little string. Useful for debugging or sending out a friendly invite to your next nerdy party!

print(type(var).__name__) # 'str'. It's like saying, "I may be jargon, but at least I'm string jargon."

Follow the Integer Rabbit Hole

Here's some sweet insider info: Python 3 unifies small and large integers into a single type 'int' with unlimited precision. No more long type as in Python 2. On the other hand, C/C++ are still throwing a party with fixed bit-width integers as their guests.

All that Glitters is not an Integer

For specially prepared integers, like a 5-star meal, you may have to hunt down the right modules (like numpy or ctypes). They offer fixed bit-widths or unsigned integers just the way grandma liked them.

Floating on an Epsilon Sea

For floating-point numbers in Python, there's a handy little attribute that can give you the float version of a treasure map (which shows the limit-lands and the epsilon sea).

import sys print(sys.float_info) # Discover attributes like max, min, and the smallest conceivable increment between float numbers (ε — epsilon)!

IPython: Your Type-laden Enchiridion

Use the ? syntax in an IPython environment when you want the low-down on a variable. Type details, documentation, and more: it's the encyclopedia of variable life!

var = 42 var? # Who needs Sherlock Holmes when you have IPython?

Unfurling the Python Type Banner

Python 2 vs Python 3: An Epic Saga

Reminder: Python 2 and Python 3 handle integers differently, mostly to keep the tension high for the sequel. Python 2 differentiates int (fixed precision) and long (arbitrary precision). Python 3 smooths things out and only uses int for both cases.

Classy Inspection

variable.__class__ gives you the class type, but it doesn't have a episode named after it.

print(var.__class__) # Also <class 'str'>, but `type(var)` has a better agent.

On a Sea of Floats

The type will show up as <class 'float'>, enhancing your floating point journey with a detailed map including negative values and minimal and maximal representations.

Variables: More than Meets the IPython

IPython goes beyond typical introspection, coming out like a knight in shining armor, offering greater analysis tools that not only tells you the variable type but includes documentation and associated metadata.