How to determine the variable type in Python?
So if you have a variable, for example:
one = 1
You want to know its type?
There are right ways and wrong ways to do just about everything in Python. Here's the right way:
>>> type(one) <type 'int'>
You can use the
__name__ attribute to get the name of the object. (This is one of the few special attributes that you need to use the
__dunder__ name to get to - there's not even a method for it in the
>>> type(one).__name__ 'int'
In Python, names that start with underscores are semantically not a part of the public API, and it's a best practice for users to avoid using them. (Except when absolutely necessary.)
type gives us the class of the object, we should avoid getting this directly. :
This is usually the first idea people have when accessing the type of an object in a method - they're already looking for attributes, so type seems weird. For example:
class Foo(object): def foo(self): self.__class__
Don't. Instead, do type(self):
class Foo(object): def foo(self): type(self)
Implementation details of ints and floats
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?
In Python, these specifics are implementation details. So, in general, we don't usually worry about this in Python. However, to sate your curiosity...
In Python 2, int is usually a signed integer equal to the implementation's word width (limited by the system). It's usually implemented as a long in C. When integers get bigger than this, we usually convert them to Python longs (with unlimited precision, not to be confused with C longs).
For example, in a 32 bit Python 2, we can deduce that int is a signed 32 bit integer:
>>> import sys >>> format(sys.maxint, '032b') '01111111111111111111111111111111' >>> format(-sys.maxint - 1, '032b') # minimum value, see docs. '-10000000000000000000000000000000'
In Python 3, the old int goes away, and we just use (Python's) long as int, which has unlimited precision.
We can also get some information about Python's floats, which are usually implemented as a double in C:
>>> sys.float_info sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1)
__class__, a semantically nonpublic API, to get the type of a variable. Use
And don't worry too much about the implementation details of Python. I've not had to deal with issues around this myself. You probably won't either, and if you really do, you should know enough not to be looking to this answer for what to do.