Marc
Marc

Reputation: 75

Python how to check the type of a variable

Basically, I need to check the type of data of which a variable is storing before replacing the data stored in the variable with the new data. For example, how to check if the variable is storing a string data or an integer data?

Source Code:

class Toy:

    #Toy Class Constructor
    def __init__(self):
        Name = "Train Engine";
        ID = "TE11";
        Price = 0.99;
        Minimum_Age = 4;

    #Return Name
    def Return_Name(self):
        print(Name)
        return Name

    #Set Name
    def Set_Name(self, Variable):
        #This is where I would need to check the type of data that the variable 'Variable' is currently storing.
        Name = Variable

    #Return ID
    def Return_ID(self):
        print(ID)
        return ID

    #Set ID
    def Set_ID(self, Variable):
        #This is where I would need to check the type of data that the variable 'Variable' is currently storing.
        ID = Variable

    #Return Price
    def Return_Price(self):
        print(Price)
        return Price

    #Set Price
    def Set_Price(self, Variable):
        #This is where I would need to check the type of data that the variable 'Variable' is currently storing.
        Price = Variable

    #Return Minimum_Age
    def print_Minimum_Age(self):
        print(Minimum_Age)
        return Minimum_Age

    #Set Minimum_Age
    def Set_Minimum_Age(self, Variable):
        #This is where I would need to check the type of data that the variable 'Variable' is currently storing.
        Minimum_Age = Variable

So basically, how should I, or are there any conventional way to check the type of data that the variable is storing?

Upvotes: 0

Views: 7305

Answers (4)

Rahul Manhas
Rahul Manhas

Reputation: 1

type(variable)

This command will return the type of the data stored by the variable.

Upvotes: 0

Nikki
Nikki

Reputation: 3

type(variable_name) returns the type of the variable

Upvotes: 0

Graipher
Graipher

Reputation: 7186

If you really want the type of a variable, and don't want to support inheriting, use the built-in type function:

if type(variable) is MyClass:
    ...

I agree with @Slam, that you should use this responsibly.

Upvotes: 0

Slam
Slam

Reputation: 8572

Proper way to do this is isinstance

if isinstance(variable, MyClass)

But think twice if you actually need this. Python uses duck-typing, so explicit checks for types is not always a good idea. If you still want to do so, consider using some abstract base or minimal valuable type for your checks.

As other people suggesting, just getting type of your variable can be done by type(variable), but in most cases its better to use isinstance, because this will make your code polymorphic - you'll automatically support instances of subclasses of target type.

Upvotes: 6

Related Questions