The best way to judge the type in Python

Python does not need to specify the specific type when defining a variable. The interpreter will automatically check the type of the variable at runtime and perform implicit type conversion as needed. Because Python is a dynamic language, it is generally not recommended. Type conversion.

For example, when performing a "+" operation, if there are data on both sides of the plus sign, perform an addition operation, if both sides are strings, perform a string concatenation operation, if both sides are lists, perform a merge operation, and even perform complex number operations.

The interpreter will call different internal methods at runtime based on the types of variables on both sides. When the variable types on both sides of the plus sign are not the same, and the type conversion cannot be performed, a TypeError exception will be thrown.

Changes of types module from Python2 to Python3


In actual development, in order to improve the robustness of the code, we still need to perform type checking. The first thing that comes to mind for type checking is to use types(), such as using types to determine an int type:

Source Code:

#! /usr/bin/env python2.6
# Author: nock.chen
from types import*
mylist =['nock',100,'100','IT']def delete(mylist, item):iftype(item) is IntType:
  mylist.remove(item)delete(mylist,100)print(mylist)

Result:

[' nock','100','IT']

We can find some commonly used types in the types module, and the results 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 refer to methods in the class
types.ClassType                #Class type
types.CodeType                 #Code block type
types.ComplexType              #Plural type
types.DictProxyType            #Dictionary proxy type
types.DictType                 #Dictionary type
types.DictionaryType           #Dictionary backup type
types.EllipsisType             #Ellipsis type
types.FileType                 #file type
types.FloatType                #Floating point type
types.FrameType                #Type of frame object
types.FunctionType             #Function type
types.GeneratorType            #Generator generated by calling generator function-iterator object type
types.GetSetDescriptorType     #Use PyGetSetDef(Such as FrameType)The type of object defined in the extension module
types.InstanceType             #Instance type
types.IntType                  #int type
types.LambdaType               #lambda type
types.ListType                 #List type
types.LongType                 #long type
types.MemberDescriptorType     #Object types defined in extension modules, including PyMemberDef, such as datetime.timedelta.days        
types.MethodType               #Method type
types.ModuleType               #module type
types.NoneType                 #None type
types.NotImplementedType       #Types of NotImplemented
types.ObjectType               #object type
types.SliceType                #  slice()Object type returned
types.StringType               #String type
types.StringTypes              #A sequence containing StringType and UnicodeType to facilitate inspection of any string object.
types.TracebackType            #In sys.exc_The type of traceback object found in traceback.
types.TupleType                #Tuple type
types.TypeType                 #Type itself
types.UnboundMethodType        #Another name for MethodType
types.UnicodeType              #Types of Unicode character strings(For example, u' spam)
types.XRangeType               #  xrange()Type of range object returned

Official website introduction: https://docs.python.org/2/library/types.html

In the Python3 version, the types module method has been significantly reduced, as follows:

types.BuiltinFunctionType              
types.BuiltinMethodType         #Type of built-in function, such as len()Or sys.exit(), And the methods of the built-in classes.(Here, "built-in" means "written in C".)
types.CodeType                  #By compile()The type of code object returned.
types.DynamicClassAttribute
types.FrameType                 #The type of frame object, as found in tb. tb_frame if tb is a traceback object.
types.FunctionType
types.GeneratorType             #Generator created by generator function-Iterator object type.
types.GetSetDescriptorType      #Use PyGetSetDef(Such as FrameType)The type of object defined in the extension module.
types.LambdaType                #User-defined functions and function types created by lambda expressions.
types.MappingProxyType
types.MemberDescriptorType
types.MethodType                #The method type of the user-defined class instance.
types.ModuleType
types.SimpleNamespace
types.TracebackType             #The type of traceback object, such as sys.exc_info()
types.new_class
types.prepare_class

Official website introduction: https://docs.python.org/3/library/types.html#module-types

It is not recommended to use type check type

During the version upgrade from Python2 to Python3 above, the type module methods have been reduced. If you use the type method, there will also be the following problems:

As shown above, the types of i and n are not the same. In fact, UserInt inherits int, so this judgment is problematic. When we expand Python built-in types, the result returned by type is not accurate enough. Up. Let's look at another example:

The type comparison result a and b are the same type, the result is obviously inaccurate. For instances of this classical class, type returns the same result, and this result is not what we want. For the built-in basic types, using tpye to check is no problem, but when applied to other situations, the type becomes unreliable.

At this time, we need to use the built-in function isinstance for type checking. An example is as follows:

isinstance(object, class_or_type_or_tuple)

Object represents an object, and classinfo can be a direct or indirect class name, basic type, or a tuple composed of them.

nock:ucode nock$ python3
Python 3.5.1(default, Dec 262015,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

Python2 has int and long types for non-floating point numbers. The maximum value of the int type cannot exceed sys.maxint, and this maximum value is platform dependent. The long integer type can be defined by appending a L at the end of the number. Obviously, it has a larger range of numbers than the int type. In Python3, there is only one type of integer type int. In most cases, it is very similar to the long integer type in Python2. Since there are no two types of integers, there is no need to use a special syntax to distinguish them. Further reading: PEP 237.

Finally, the best way to judge your type in Python is to use the built-in function isinstance to complete the best experience.

Official website introduction: https://docs.python.org/3/library/functions.html#isinstance

Recommended Posts

The best way to judge the type in Python
Python string to judge the password strength
How to use the round function in python
How to use the zip function in Python
How to use the format function in python
How to understand the introduction of packages in Python
What are the ways to open files in python
How to find the area of a circle in python
The usage of wheel in python
How to wrap in python code
How to omit parentheses in Python
How to write classes in python
​What are the numbers in Python?
How to read Excel in Python
How to view errors in python
How to write return in python
How to view the python module
How to understand variables in Python
How to clear variables in python
The usage of tuples in python
How to use SQLite in Python
Understanding the meaning of rb in python
How to use and and or in Python
How to delete cache files in python
How to introduce third-party modules in Python
How to represent null values in python
The usage of Ajax in Python3 crawler
How to save text files in python
How to write win programs in python
How to run id function in python
How to install third-party modules in Python
How to custom catch errors in python
How to write try statement in python
How to define private attributes in Python
How to add custom modules in Python
How to understand global variables in Python
How to view installed modules in python
Python novice learns to use the library
How to learn the Python time module
How to open python in different systems
Is a number in python a variable type
How to sort a dictionary in python
How to add background music in python
How to represent relative path in python
Python randomly shuffles the elements in the list
What is the function of adb in python
How to program based on interfaces in Python
Python uses the email module to send mail
How to install python in ubuntu server environment
How to simulate gravity in a Python game
What does the tab key in python mean
Python implements the shuffling of the cards in Doudizhu
How to open the ubuntu system in win10
First acquainted with python, the grammatical rules in python
How to use code running assistant in python
How to enter python through the command line
How to set code auto prompt in python
How to switch the hosts file using python
Teach you how to write games in python
How to delete files and directories in python
Introduction to the use of Hanlp in ubuntu