Python does not specify a specific type when defining a variable. The interpreter will automatically check the type of a variable at runtime and perform implicit type conversions as needed. Since Python is a dynamic language, type conversions are generally not recommended.
For example, when you do a “+”, you add data on both sides, you concatenate strings on both sides, you combine lists on both sides, and you can even do complex numbers.
The interpreter calls different internal methods at run time depending on the type of the variables on either side. When the two sides of the plus sign are of different types and cannot be converted, TypeError is raised.
Changes to the types module from Python2 to Python3
In real development, type checking is needed to improve code robustness. The first thing that comes to mind is types(), such as types for an int:
Source Code:
#! The/usr/bin/env python2.6
#Author: nock.chen
from types import *
mylist = ['nock', 100, '100'.'IT']
def delete(mylist, item):
if type(item) is IntType:
mylist.remove(item)
delete(mylist, 100)
print(mylist)
Copy the code
Result:
['nock'.'100'.'IT']
Copy the code
We can find some common types in the types module, as shown in 2.6.9:
types.BooleanType # bool type
types.BufferType # buffer type
types.BuiltinFunctionType # Built-in functions such as len()
types.BuiltinMethodType # Built-in methods, which refer to methods in a class
types.ClassType # class type
types.CodeType Type of code block
types.ComplexType # plural type
types.DictProxyType Dictionary proxy type
types.DictType # dictionary type
types.DictionaryType # dictionary alternate types
types.EllipsisType # Ellipsis type
types.FileType # file type
types.FloatType Float type
types.FrameType The type of the frame object
types.FunctionType # function type
types.GeneratorType The type of generator-iterator generated by calling a generator function
types.GetSetDescriptorType The type of the object defined in the extension module with PyGetSetDef(such as FrameType)
types.InstanceType # instance type
types.IntType # type int
types.LambdaType # lambda type
types.ListType # list type
types.LongType # long
types.MemberDescriptorType # Object types defined in extension modules, including PyMemberDef, such as datetime.timedelta.days
types.MethodType # method type
types.ModuleType # the module type
types.NoneType # None type
types.NotImplementedType # NotImplemented
types.ObjectType # object type
types.SliceType The type of object returned by # slice()
types.StringType # string type
types.StringTypes # A sequence containing StringType and UnicodeType to facilitate checking any string object.
types.TracebackType # The type of traceback object found in sys.exc_traceback.
types.TupleType # tuple type
types.TypeType # The type itself
types.UnboundMethodType # another name for MethodType
types.UnicodeType The type of a string (for example, u 'spam)
types.XRangeType The type of the range object returned by # xrange()
Copy the code
Website: https://docs.python.org/2/library/types.html
By Python3, the types module methods have been significantly reduced as follows:
types.BuiltinFunctionType
types.BuiltinMethodType # The type of the built-in function, such as len() or sys.exit(), and the methods of the built-in class. (Here, "built in" means "written in C.")
types.CodeType # Type of code object returned with compile().
types.DynamicClassAttribute
types.FrameType Type of frame object, as found in TB. Tb_frame If TB is a Traceback object.
types.FunctionType
types.GeneratorType The type of generator - iterator object created by a generator function.
types.GetSetDescriptorType The type of the object defined in the extension module with PyGetSetDef(such as FrameType).
types.LambdaType # User-defined functions and their types created by lambda expressions.
types.MappingProxyType
types.MemberDescriptorType
types.MethodType User-defined method types for class instances.
types.ModuleType
types.SimpleNamespace
types.TracebackType # Traceback object type, such as sys.exc_info()
types.new_class
types.prepare_class
Copy the code
Website: https://docs.python.org/3/library/types.html#module-types
Type Check type is not recommended
The types module methods have been reduced during the upgrade from Python2 to Python3 above. The type method also has the following problems:
As shown above, the types of I and n are different, and UserInt inherits from int, so this judgment is problematic. When we extend Python’s built-in types, type returns inaccurate results. Let’s look at another example:
In this case, we need to use the built-in isinstance function for type checking, as shown in the following example:
isinstance(object, class_or_type_or_tuple)
Copy the code
Object represents an object. Classinfo can be a direct or indirect class name, a primitive type, or a tuple composed of them.
Ucode nock$python3 Python 3.5.1 (default, Dec 26 2015, 18:08:53) [GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on Darwin Type"help"."copyright"."credits" or "license" for more information.
>>> isinstance(2, float)
False
>>> isinstance(2, int)
True
>>> isinstance((2, 3), list)
False
>>> isinstance((2, 3), tuple)
True
>>> isinstance({'name': 'nock'}, tuple)
False
>>> isinstance({'name': 'nock'}, dict)
True
>>> isinstance([1, 100, 101], (str, list, tuple))
True
>>> isinstance(2 ** 31, dict)
False
>>> isinstance(2 ** 31, long)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'long' is not defined
>>> isinstance(2 ** 31, int)
True
Copy the code
Python2 has int and long types for non-floating point numbers. The maximum value of an int cannot exceed sys.maxint, and the maximum value is platform dependent. Long integers can be defined by enclosing an L at the end of a number, which is obviously a larger range of numbers than an int. In Python3, there is only one integer type, int, and for the most part, it looks a lot like the long integers in Python2. Since there are no longer two types of integers, there is no need to use special syntax to distinguish between them, read more: PEP 237.
Finally, the best way to determine your type in Python is to use the built-in isinstance function for the best experience.
Website: https://docs.python.org/3/library/functions.html#isinstance