[python] How to determine a Python variable's type?

How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?

How do I view it?

This question is related to python types unsigned signed 16-bit

The answer is


Use the type() builtin function:

>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True

To check if a variable is of a given type, use isinstance:

>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False

Note that Python doesn't have the same types as C/C++, which appears to be your question.


print type(variable_name)

I also highly recommend the IPython interactive interpreter when dealing with questions like this. It lets you type variable_name? and will return a whole list of information about the object including the type and the doc string for the type.

e.g.

In [9]: var = 123

In [10]: var?
Type:       int
Base Class: <type 'int'>
String Form:    123
Namespace:  Interactive
Docstring:
    int(x[, base]) -> integer

Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead.


Do you mean in Python or using ctypes?

In the first case, you simply cannot - because Python does not have signed/unsigned, 16/32 bit integers.

In the second case, you can use type():

>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>

For more reference on ctypes, an its type, see the official documentation.


For python2.x, use

print type(variable_name)

For python3.x, use

print(type(variable_name))

You may be looking for the type() built-in function.

See the examples below, but there's no "unsigned" type in Python just like Java.

Positive integer:

>>> v = 10
>>> type(v)
<type 'int'>

Large positive integer:

>>> v = 100000000000000
>>> type(v)
<type 'long'>

Negative integer:

>>> v = -10
>>> type(v)
<type 'int'>

Literal sequence of characters:

>>> v = 'hi'
>>> type(v)
<type 'str'>

Floating point integer:

>>> v = 3.14159
>>> type(v)
<type 'float'>

It really depends on what level you mean. In Python 2.x, there are two integer types, int (constrained to sys.maxint) and long (unlimited precision), for historical reasons. In Python code, this shouldn't make a bit of difference because the interpreter automatically converts to long when a number is too large. If you want to know about the actual data types used in the underlying interpreter, that's implementation dependent. (CPython's are located in Objects/intobject.c and Objects/longobject.c.) To find out about the systems types look at cdleary answer for using the struct module.


Python doesn't have such types as you describe. There are two types used to represent integral values: int, which corresponds to platform's int type in C, and long, which is an arbitrary precision integer (i.e. it grows as needed and doesn't have an upper limit). ints are silently converted to long if an expression produces result which cannot be stored in int.


You may be looking for the type() built-in function.

See the examples below, but there's no "unsigned" type in Python just like Java.

Positive integer:

>>> v = 10
>>> type(v)
<type 'int'>

Large positive integer:

>>> v = 100000000000000
>>> type(v)
<type 'long'>

Negative integer:

>>> v = -10
>>> type(v)
<type 'int'>

Literal sequence of characters:

>>> v = 'hi'
>>> type(v)
<type 'str'>

Floating point integer:

>>> v = 3.14159
>>> type(v)
<type 'float'>

It really depends on what level you mean. In Python 2.x, there are two integer types, int (constrained to sys.maxint) and long (unlimited precision), for historical reasons. In Python code, this shouldn't make a bit of difference because the interpreter automatically converts to long when a number is too large. If you want to know about the actual data types used in the underlying interpreter, that's implementation dependent. (CPython's are located in Objects/intobject.c and Objects/longobject.c.) To find out about the systems types look at cdleary answer for using the struct module.


One more way using __class__:

>>> a = [1, 2, 3, 4]
>>> a.__class__
<type 'list'>
>>> b = {'key1': 'val1'}
>>> b.__class__
<type 'dict'>
>>> c = 12
>>> c.__class__
<type 'int'>

Use the type() builtin function:

>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True

To check if a variable is of a given type, use isinstance:

>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False

Note that Python doesn't have the same types as C/C++, which appears to be your question.


Simple, for python 3.4 and above

print (type(variable_name))

Python 2.7 and above

print type(variable_name)

Python doesn't have such types as you describe. There are two types used to represent integral values: int, which corresponds to platform's int type in C, and long, which is an arbitrary precision integer (i.e. it grows as needed and doesn't have an upper limit). ints are silently converted to long if an expression produces result which cannot be stored in int.


print type(variable_name)

I also highly recommend the IPython interactive interpreter when dealing with questions like this. It lets you type variable_name? and will return a whole list of information about the object including the type and the doc string for the type.

e.g.

In [9]: var = 123

In [10]: var?
Type:       int
Base Class: <type 'int'>
String Form:    123
Namespace:  Interactive
Docstring:
    int(x[, base]) -> integer

Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead.


Examples of simple type checking in Python:

assert type(variable_name) == int

assert type(variable_name) == bool

assert type(variable_name) == list

It may be little irrelevant. but you can check types of an object with isinstance(object, type) as mentioned here.


print type(variable_name)

I also highly recommend the IPython interactive interpreter when dealing with questions like this. It lets you type variable_name? and will return a whole list of information about the object including the type and the doc string for the type.

e.g.

In [9]: var = 123

In [10]: var?
Type:       int
Base Class: <type 'int'>
String Form:    123
Namespace:  Interactive
Docstring:
    int(x[, base]) -> integer

Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead.


It really depends on what level you mean. In Python 2.x, there are two integer types, int (constrained to sys.maxint) and long (unlimited precision), for historical reasons. In Python code, this shouldn't make a bit of difference because the interpreter automatically converts to long when a number is too large. If you want to know about the actual data types used in the underlying interpreter, that's implementation dependent. (CPython's are located in Objects/intobject.c and Objects/longobject.c.) To find out about the systems types look at cdleary answer for using the struct module.


print type(variable_name)

I also highly recommend the IPython interactive interpreter when dealing with questions like this. It lets you type variable_name? and will return a whole list of information about the object including the type and the doc string for the type.

e.g.

In [9]: var = 123

In [10]: var?
Type:       int
Base Class: <type 'int'>
String Form:    123
Namespace:  Interactive
Docstring:
    int(x[, base]) -> integer

Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead.


Do you mean in Python or using ctypes?

In the first case, you simply cannot - because Python does not have signed/unsigned, 16/32 bit integers.

In the second case, you can use type():

>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>

For more reference on ctypes, an its type, see the official documentation.


Just do not do it. Asking for something's type is wrong in itself. Instead use polymorphism. Find or if necessary define by yourself the method that does what you want for any possible type of input and just call it without asking about anything. If you need to work with built-in types or types defined by a third-party library, you can always inherit from them and use your own derivatives instead. Or you can wrap them inside your own class. This is the object-oriented way to resolve such problems.

If you insist on checking exact type and placing some dirty ifs here and there, you can use __class__ property or type function to do it, but soon you will find yourself updating all these ifs with additional cases every two or three commits. Doing it the OO way prevents that and lets you only define a new class for a new type of input instead.


It really depends on what level you mean. In Python 2.x, there are two integer types, int (constrained to sys.maxint) and long (unlimited precision), for historical reasons. In Python code, this shouldn't make a bit of difference because the interpreter automatically converts to long when a number is too large. If you want to know about the actual data types used in the underlying interpreter, that's implementation dependent. (CPython's are located in Objects/intobject.c and Objects/longobject.c.) To find out about the systems types look at cdleary answer for using the struct module.


Python doesn't have such types as you describe. There are two types used to represent integral values: int, which corresponds to platform's int type in C, and long, which is an arbitrary precision integer (i.e. it grows as needed and doesn't have an upper limit). ints are silently converted to long if an expression produces result which cannot be stored in int.


Just do not do it. Asking for something's type is wrong in itself. Instead use polymorphism. Find or if necessary define by yourself the method that does what you want for any possible type of input and just call it without asking about anything. If you need to work with built-in types or types defined by a third-party library, you can always inherit from them and use your own derivatives instead. Or you can wrap them inside your own class. This is the object-oriented way to resolve such problems.

If you insist on checking exact type and placing some dirty ifs here and there, you can use __class__ property or type function to do it, but soon you will find yourself updating all these ifs with additional cases every two or three commits. Doing it the OO way prevents that and lets you only define a new class for a new type of input instead.


Use the type() builtin function:

>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True

To check if a variable is of a given type, use isinstance:

>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False

Note that Python doesn't have the same types as C/C++, which appears to be your question.


a = "cool"
type(a)

//result 'str'
<class 'str'>
or 
do 
`dir(a)` 
to see the list of inbuilt methods you can have on the variable.

It is so simple. You do it like this.

print(type(variable_name))

The question is somewhat ambiguous -- I'm not sure what you mean by "view". If you are trying to query the type of a native Python object, @atzz's answer will steer you in the right direction.

However, if you are trying to generate Python objects that have the semantics of primitive C-types, (such as uint32_t, int16_t), use the struct module. You can determine the number of bits in a given C-type primitive thusly:

>>> struct.calcsize('c') # char
1
>>> struct.calcsize('h') # short
2
>>> struct.calcsize('i') # int
4
>>> struct.calcsize('l') # long
4

This is also reflected in the array module, which can make arrays of these lower-level types:

>>> array.array('c').itemsize # char
1

The maximum integer supported (Python 2's int) is given by sys.maxint.

>>> import sys, math
>>> math.ceil(math.log(sys.maxint, 2)) + 1 # Signedness
32.0

There is also sys.getsizeof, which returns the actual size of the Python object in residual memory:

>>> a = 5
>>> sys.getsizeof(a) # Residual memory.
12

For float data and precision data, use sys.float_info:

>>> 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)

You may be looking for the type() built-in function.

See the examples below, but there's no "unsigned" type in Python just like Java.

Positive integer:

>>> v = 10
>>> type(v)
<type 'int'>

Large positive integer:

>>> v = 100000000000000
>>> type(v)
<type 'long'>

Negative integer:

>>> v = -10
>>> type(v)
<type 'int'>

Literal sequence of characters:

>>> v = 'hi'
>>> type(v)
<type 'str'>

Floating point integer:

>>> v = 3.14159
>>> type(v)
<type 'float'>

One more way using __class__:

>>> a = [1, 2, 3, 4]
>>> a.__class__
<type 'list'>
>>> b = {'key1': 'val1'}
>>> b.__class__
<type 'dict'>
>>> c = 12
>>> c.__class__
<type 'int'>

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:

Use type

>>> 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 inspect module.)

>>> type(one).__name__
'int'

Don't use __class__

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.)

Since type gives us the class of the object, we should avoid getting this directly. :

>>> one.__class__

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)

Conclusion

Don't use __class__, a semantically nonpublic API, to get the type of a variable. Use type instead.

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.


It is so simple. You do it like this.

print(type(variable_name))

The question is somewhat ambiguous -- I'm not sure what you mean by "view". If you are trying to query the type of a native Python object, @atzz's answer will steer you in the right direction.

However, if you are trying to generate Python objects that have the semantics of primitive C-types, (such as uint32_t, int16_t), use the struct module. You can determine the number of bits in a given C-type primitive thusly:

>>> struct.calcsize('c') # char
1
>>> struct.calcsize('h') # short
2
>>> struct.calcsize('i') # int
4
>>> struct.calcsize('l') # long
4

This is also reflected in the array module, which can make arrays of these lower-level types:

>>> array.array('c').itemsize # char
1

The maximum integer supported (Python 2's int) is given by sys.maxint.

>>> import sys, math
>>> math.ceil(math.log(sys.maxint, 2)) + 1 # Signedness
32.0

There is also sys.getsizeof, which returns the actual size of the Python object in residual memory:

>>> a = 5
>>> sys.getsizeof(a) # Residual memory.
12

For float data and precision data, use sys.float_info:

>>> 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)

Do you mean in Python or using ctypes?

In the first case, you simply cannot - because Python does not have signed/unsigned, 16/32 bit integers.

In the second case, you can use type():

>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>

For more reference on ctypes, an its type, see the official documentation.


It may be little irrelevant. but you can check types of an object with isinstance(object, type) as mentioned here.


The question is somewhat ambiguous -- I'm not sure what you mean by "view". If you are trying to query the type of a native Python object, @atzz's answer will steer you in the right direction.

However, if you are trying to generate Python objects that have the semantics of primitive C-types, (such as uint32_t, int16_t), use the struct module. You can determine the number of bits in a given C-type primitive thusly:

>>> struct.calcsize('c') # char
1
>>> struct.calcsize('h') # short
2
>>> struct.calcsize('i') # int
4
>>> struct.calcsize('l') # long
4

This is also reflected in the array module, which can make arrays of these lower-level types:

>>> array.array('c').itemsize # char
1

The maximum integer supported (Python 2's int) is given by sys.maxint.

>>> import sys, math
>>> math.ceil(math.log(sys.maxint, 2)) + 1 # Signedness
32.0

There is also sys.getsizeof, which returns the actual size of the Python object in residual memory:

>>> a = 5
>>> sys.getsizeof(a) # Residual memory.
12

For float data and precision data, use sys.float_info:

>>> 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)

Do you mean in Python or using ctypes?

In the first case, you simply cannot - because Python does not have signed/unsigned, 16/32 bit integers.

In the second case, you can use type():

>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>

For more reference on ctypes, an its type, see the official documentation.


Examples of simple type checking in Python:

assert type(variable_name) == int

assert type(variable_name) == bool

assert type(variable_name) == list

Use the type() builtin function:

>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True

To check if a variable is of a given type, use isinstance:

>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False

Note that Python doesn't have the same types as C/C++, which appears to be your question.


The question is somewhat ambiguous -- I'm not sure what you mean by "view". If you are trying to query the type of a native Python object, @atzz's answer will steer you in the right direction.

However, if you are trying to generate Python objects that have the semantics of primitive C-types, (such as uint32_t, int16_t), use the struct module. You can determine the number of bits in a given C-type primitive thusly:

>>> struct.calcsize('c') # char
1
>>> struct.calcsize('h') # short
2
>>> struct.calcsize('i') # int
4
>>> struct.calcsize('l') # long
4

This is also reflected in the array module, which can make arrays of these lower-level types:

>>> array.array('c').itemsize # char
1

The maximum integer supported (Python 2's int) is given by sys.maxint.

>>> import sys, math
>>> math.ceil(math.log(sys.maxint, 2)) + 1 # Signedness
32.0

There is also sys.getsizeof, which returns the actual size of the Python object in residual memory:

>>> a = 5
>>> sys.getsizeof(a) # Residual memory.
12

For float data and precision data, use sys.float_info:

>>> 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)

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:

Use type

>>> 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 inspect module.)

>>> type(one).__name__
'int'

Don't use __class__

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.)

Since type gives us the class of the object, we should avoid getting this directly. :

>>> one.__class__

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)

Conclusion

Don't use __class__, a semantically nonpublic API, to get the type of a variable. Use type instead.

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.


For python2.x, use

print type(variable_name)

For python3.x, use

print(type(variable_name))

a = "cool"
type(a)

//result 'str'
<class 'str'>
or 
do 
`dir(a)` 
to see the list of inbuilt methods you can have on the variable.

Simple, for python 3.4 and above

print (type(variable_name))

Python 2.7 and above

print type(variable_name)

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to types

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean

Examples related to unsigned

Unsigned values in C How to use the unsigned Integer in Java 8 and Java 9? How to convert signed to unsigned integer in python should use size_t or ssize_t Declaring an unsigned int in Java Is unsigned integer subtraction defined behavior? Calculating bits required to store decimal number How to cast or convert an unsigned int to int in C? Difference between signed / unsigned char Can we make unsigned byte in Java

Examples related to signed

How to convert signed to unsigned integer in python should use size_t or ssize_t What is the difference between “int” and “uint” / “long” and “ulong”? C++ convert hex string to signed integer Iteration over std::vector: unsigned vs signed index variable How to determine a Python variable's type? Signed versus Unsigned Integers

Examples related to 16-bit

How to execute 16-bit installer on 64-bit Win7? How to determine a Python variable's type?