How To Get The Type Of A Variable In Python

4 min read

Python's dynamic typing system is one of its most powerful features, but it also introduces a common challenge for beginners and intermediate developers alike: knowing exactly what type of data a variable holds at any given moment. Think about it: in this article, we'll explore the most direct and Pythonic ways to retrieve a variable's type, dive into the nuances of the built-in type() function, and examine how isinstance() extends this capability for more dependable type checking. In practice, whether you're debugging a stubborn error, validating user input, or simply trying to understand the behavior of your code, being able to inspect a variable's type is an essential skill. By the end, you'll not only know which method to use in different scenarios but also understand why type inspection matters for writing cleaner, more maintainable code.

Using the type() Function

The most straightforward way to get the type of a variable in Python is the built-in type() function. It returns the class type of the object passed to it. This function works with almost every Python object: numbers, strings, lists, dictionaries, custom objects, and more But it adds up..

x = 42
print(type(x))  # 

y = "Hello, World!"
print(type(y))  # 

z = [1, 2, 3]
print(type(z))  # 

The type() function is invaluable when you need a quick, unambiguous answer about what kind of data you're dealing with. It returns the exact type object, which can then be compared, stored, or used in further logic. To give you an idea, you might store the result in a variable for later use:

variable = input("Enter something: ")
variable_type = type(variable)
print(f"The input is of type: {variable_type}")

One important detail: type() returns the most specific type available. If a variable holds an integer, you'll get int; if it holds a float, you'll get float. This precision makes type() the go-to choice for many simple type-checking tasks It's one of those things that adds up..

type() vs isinstance(): Choosing the Right Tool

While type() is direct, Python developers often reach for isinstance() when working with inheritance or multiple possible types. On top of that, the isinstance() function checks whether a variable is an instance of a specified class or a tuple of classes. Unlike type(), which returns the exact type, isinstance() returns a boolean: True or False.

value = 3.14
print(isinstance(value, float))

### Diving Deeper into `isinstance()`

Having seen that `isinstance()` returns a Boolean rather than an object, it becomes clear why many real‑world programs prefer it. In practice, its primary strength lies in handling **inheritance hierarchies**. In practice, when you create a subclass—say, `Dog` inherits from `Animal`—the call `isinstance(myself, Animal)` evaluates to `True`, whereas `type(yourself) is Animal` would always be `False`. This subtlety saves you from accidentally rejecting instances that should legitimately belong to a parent class.

#### Basic Usage

```python
value = 3.14
print(isinstance(value, float))          # → True

# Even though 3.14 is stored as a floating‑point number

#### Advanced Scenarios with `isinstance()`

When a variable may belong to several concrete classes, `isinstance()` accepts a **tuple** of types. This lets you write a single test that covers all acceptable alternatives without resorting to a chain of `or` statements.

```python
def process_number(value):
    if isinstance(value, (int, float)):
        return value * 2
    raise TypeError("Unsupported numeric type")

print(process_number(5))      # 10
print(process_number(2.7))    # 5.4

The same pattern works for user‑defined class hierarchies. Suppose you have a base class Shape and two concrete subclasses Circle and Square. A function that draws any shape can verify its argument like this:

class Shape: pass
class Circle(Shape): pass
class Square(Shape): pass

def draw(shape):
    if not isinstance(shape, Shape):
        raise ValueError("Object must be a Shape or subclass")
    # drawing logic here

Because isinstance() follows the inheritance chain, a Circle instance will satisfy the check even though its exact class is not Shape.

Distinguishing None from Other Types

None is a singleton object of type type(None). A common source of bugs is treating None as a regular value. isinstance() can explicitly guard against this:

def fetch_data(source):
    if isinstance(source, str) and source is not None:
        return source.upper()
    return None

Type Narrowing in Conditional Blocks

In functions that accept union types, isinstance() can be used to narrow the type inside a conditional block, giving static type checkers more information.

def describe(obj):
    if isinstance(obj, str):
        # At this point mypy knows obj is a str
        return f"String of length {len(obj)}"
    elif isinstance(obj, (int, float)):
        # mypy now sees obj as a numeric type
        return f"Number: {obj}"
    else:
        return "Unknown"

Beyond isinstance() – issubclass() and type()

While isinstance() tells you whether an object belongs to a class (or a set of classes), issubclass() answers whether a class is a subclass of another. This is handy when you need to validate class objects themselves, not instances.

class Animal: pass
class Dog(Animal): pass
class Cat(Animal): pass

if issubclass(Dog, Animal):
    print("Dog is an Animal")   # prints

type() remains useful when you need the exact class object, for example when building a registry keyed by class name:

registry = {}
registry[type('List')] = lambda: []
registry[type('Dict')]
Newest Stuff

New Arrivals

Cut from the Same Cloth

Others Found Helpful

Thank you for reading about How To Get The Type Of A Variable In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home