How do I check whether a variable is an integer?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you need to do this, do
unless you are in Python 2.x in which case you want
Do not use
type. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclassint, your new class should register as anint, whichtypewill not do:This adheres to Python’s strong polymorphism: you should allow any object that behaves like an
int, instead of mandating that it be one.BUT
The classical Python mentality, though, is that it’s easier to ask forgiveness than permission. In other words, don’t check whether
xis an integer; assume that it is and catch the exception results if it isn’t:This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.