Python's Inspect Module 2

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/mldxs/article/details/8652010

first, the inspect module mainly provides four kinds of use :

(1). Type check for modules, frames, functions, etc.

(2). Get the source code

(3). Get information about the parameters of a class or function

(4). Parsing the Stack

Use the inspect module to provide self-reflection, here is some introduction to introspection, first of all, an example to look at the objects and related concepts that may be used in this article.

Import SYS # module, sys points to this module object

def foo (): # function, Foo points to this function object
Pass

Class Cat (Object): # class, Cat points to this class object
def __init__ (self, name = ' Kitty '):
Self.name = Name

def sayhi (self): # instance method, Sayhi point to this method object, use class or instance. Sayhi Access
Print self.name, ' says hi! ' # access the field named name, using the instance. Name Access

Cat = Cat () # Cat is an instance object of the Cat class
Print Cat.sayhi # When accessing an instance method using the class name, the method is unbound (unbound)
Print Cat.sayhi # When accessing an instance method using an instance, the method is bound (bound)

Sometimes we encounter the need to execute a method of an object, or to assign a value to a field of an object, and the method name or field name cannot be determined when coding the code, and it needs to be entered in the form of a parameter pass string. As a concrete example: when we need to implement a generic dbm framework, we may need to assign values to the fields of the data object, but we cannot predict what fields the data objects used in this framework have, in other words, we need some mechanism to access unknown properties when we write the framework.

This mechanism is called reflection (which in turn allows the object to tell us what he is), or introspection (let the object tell us what he is, ok I admit I made up my mind in parentheses--#), used to implement information that gets unknown objects at run time. Reflection is a frightening noun, sounding inscrutable, in general programming language reflection is slightly more complex than other concepts, generally speaking as a high-level theme, but in Python it is very simple to use and almost feel different from other code, The functions and methods obtained by using reflection can be called directly as usual, and the instance can be constructed directly after the class is obtained, but the obtained field cannot be directly assigned because it is actually another reference to the same place, and the assignment can only change the current reference.

1. Accessing the properties of an object
Several built-in methods are listed below that can be used to check or access the properties of an object. These methods can be used for any object, not just the cat instance object in the example, and everything in Python is an object.

cat = Cat (' Kitty ')
Print Cat.name # accessing instance Properties
Cat.sayhi () # Invoke instance method

Print dir (cat) # Gets the property name of the instance, returned as a list
if Hasattr (cat, ' name '): # Check if the instance has this property
setattr (cat, ' name ', ' Tiger ') # same as:a.name = ' Tiger '
Print getattr (cat, ' name ') # same As:print a.name
getattr (cat, ' Sayhi ') () # same as:cat.sayHi ()

Dir ([obj]): Calling this method returns a list containing most of the property names of obj (some special attributes are not included). The default value of obj is the current module object.
Hasattr (obj, attr): This method is used to check if obj has a property named Attr and returns a Boolean value.
GetAttr (obj, attr): Calling this method returns the value of the property named attr value in obj, such as Obj.bar if attr is ' bar '.
SetAttr (obj, attr, Val): Calling this method assigns a value of Val to the property named attr of obj. For example, if attr is ' bar ', it is equivalent to Obj.bar = val.

2. Accessing the metadata of an object
When you use Dir () on an object that you construct, you may find that many of the attributes in the list are not defined by you. These properties generally hold the object's metadata, such as the class's __name__ property, which holds the class name. Most of these properties can be modified, but the meaning of changing them is not very large; modifying some of these properties, such as Function.func_code, can also lead to problems that are difficult to spot, so change the name or whatever, and other properties don't change without knowing the consequences.

Next, you'll list some special properties for a particular object. In addition, Python's documentation mentions that some of the properties may not always be available, and the following will be marked with a red asterisk * , which you can turn on before using the interpreter.

2.0. Preparation: Determining the type of object
All Python built-in types are defined in the types module, and the specific type of the object can be determined with the built-in method Isinstance ().

Isinstance (object, ClassInfo): Checks if object is a type that is enumerated in ClassInfo and returns a Boolean value. ClassInfo can be a specific type, or it can be a tuple or list of more than one type.
The types module only defines the type, and the inspect module encapsulates a number of methods for checking the type, which is easier than using the types module directly, so there is no more introduction to types, and you can view the document description of the types module directly if necessary. The inspect module is described in section 3rd of this article.

2.1. Modules (module)
__DOC__: Document String. If the module does not have a document, this value is none.
*__name__: The module name is always defined, even if you use import. As it takes an alias, or assigns another variable name.
*__dict__: contains a dictionary of the property names-attributes available in the module; The object that can be accessed by using the module name. Property name.
__FILE__: Contains the file path for the module. It is important to note that the built-in module does not have this property, and accessing it throws an exception!

Import Fnmatch as M

Print M. __doc__. Splitlines () [0] # Filename matching with shell patterns.
Print M. __name__ # Fnmatch
Print M. __file__ #/USR/LIB/PYTHON2.6/FNMATCH.PYC
Print M. __dict__. Items () [0] # (' Fnmatchcase ',)

2.2. Classes (Class)
__DOC__: Document String. If the class does not have a document, this value is none.
*__name__: is always the name of the class at the time of definition.
*__dict__: Contains a dictionary of the property names-Properties available in the class; The object that can be accessed by using the class name. Property name.
__MODULE__: The module name that contains the definition of the class; It is important to note that the module name is in string form instead of the module object.
*__bases__: The tuple of the immediate parent class object, but does not contain other classes in the upper layer of the inheritance tree, such as the parent class of the parent class.

Print cat.__doc__ # None
Print Cat. __NAME__ # Cat
Print Cat. __MODULE__ # __main__
Print Cat. __bases__ # (,)
Print Cat. __dict__ # {' __module__ ': ' __main__ ', ...}

2.3. Example (instance)
An instance is an object that is later instantiated by a class.

*__dict__: contains a dictionary of available property names-Properties.
*__class__: The Class object for the instance. For class cat,cat.__class__ = = Cat is True.

Print cat.__dict__
Print Cat. __class__
Print Cat. __class__ = = Cat # True

2.4. Built-in functions and methods (built-in functions and methods)
By definition, the built-in (built-in) module refers to a module written in C, which can be viewed through the Sys module's builtin_module_names field to see which modules are built-in. The functions and methods in these modules can use fewer properties, but generally do not need to view their information in code.

__DOC__: A document for a function or method.
__NAME__: The name of the function or method definition.
__self__: The method is available only, and if it is bound (bound), it is none for the class that called the method (if it is a class method) or an instance (if it is an instance method).
*__module__: The name of the module in which the function or method resides.

2.5. Functions (function)
This is specifically a non-built function. Note that defining a method with Def in a class is a different concept, although methods and functions have similar behavior.

__DOC__: A document for a function, or a property name to Func_doc.
__NAME__: The function name when the functions are defined, or Func_name with the property name.
*__module__: The module name that contains the function definition, as well as the module name and not the module object.
*__dict__: The available properties of a function, or it can be func_dict with the property name.
Do not forget that functions are also objects, you can use functions. property name access to the property (if the property does not exist when it is assigned), or by using the built-in function hasattr/getattr/setattr () access. However, it is not very important to save the property in a function.
Func_defaults: This property holds the parameter default value tuple for the function, because the default value is always the last parameter, so the form that does not use the dictionary can also correspond to the parameter.
Func_code: This property points to a code object that corresponds to the function, and the code object defines some other special properties, which are described separately below.
Func_globals: This property points to the current global namespace instead of the global namespace when the function is defined, and is not very useful and is read-only.
*func_closure: This property is valid only if the function is a closure, pointing to a tuple of the variable cell that holds the referenced external function, or none if the function is not an intrinsic function. This property is also read-only.

2.6. Methods (method)
The method is not a function, but it can be understood to add a layer of shell outside the function, and after getting the actual function in the method, you can use the properties of section 2.5.

__DOC__: Same as function.
__NAME__: Same as function.
*__module__: same as function.
Im_func: Use this property to get a reference to the actual function object in the method. In addition, if the version is more than 2.6, you can also use the property name __func__.
Im_self: If it is a bound (bound), it points to the class that called the method (if it is a class method) or an instance (if it is an instance method), otherwise none. If the version is more than 2.6, you can also use the property name __self__.
Im_class: The class that actually calls the method, or the instance that actually calls the method. Note the class that is not the definition of the method, if there is an inheritance relationship.

im = Cat.sayhi
Print Im.im_func
Print Im.im_self # Cat
Print Im.im_class # Cat

The general example method is discussed here, and there are two special methods, the class method (Classmethod) and the static method (Staticmethod), respectively. A class method is still a method, but because it needs to be called with a class name, he is always bound (me:?); Whereas a static method can be seen as a function in the namespace of a class (a function that needs to be called with a class name), it can use only the properties of the function, not the properties of the method.

2.7. Generator (Generator)
The generator is an object returned by calling a generator function (generator functions), and is used more iteratively for collection objects.

__iter__: is simply an iterative token.
Gi_code: The code object that corresponds to the generator.
Gi_frame: The frame object that corresponds to the generator.
Gi_running: Whether the generator function is executing. The generator function is in the frozen state after yield, before the next line of code that executes yield, at which point the value of this property is 0.
Next|close|send|throw: This is a few callable methods that do not contain metadata information and how to use the related documents that can view the builder.

def Gen ():
    for N in xrange (5) :
        yield n
g = Gen ()
print G                       # & Lt;generator Object Gen at 0x...>
print g.gi_code           # <code Object Gen at 0x...>
print g.gi_frame     & nbsp   # <frame object at 0x...>
print g.gi_running      # 0
print G.next ()            # 0
print G.next ()            # 1

For N in G:
Print N, # 2 3 4

The next discussion is a few of the built-in object types that are not commonly used. These types should rarely be contacted during normal coding, unless you are implementing an interpreter or development environment yourself. So here are only a few properties, if you need a complete attribute table or want to learn more, you can view the reference documents listed at the end of the article.

2.8. Code block
Code blocks can be compiled from class source code, function source code, or a simple statement code. Here we only consider the case when it refers to a function, and we have mentioned in section 2.5 that you can use the Func_code property of the function to get to it. The properties of code are all read-only.

Co_argcount: The total number of normal parameters, excluding * parameters and * * parameters.
Co_names: A tuple of all parameter names (including * parameters and * * parameters) and local variable names.
Co_varnames: A tuple of all local variable names.
Co_filename: The file name where the source code resides.
Co_flags: This is a numeric value, and each bits contains specific information. The more concerned is 0b100 (0x4) and 0b1000 (0x8), if co_flags & 0b100! = 0, the description uses the *args parameter; if Co_flags & 0b1000! = 0, the **kwargs parameter is used. Also, if Co_flags & 0b100000 (0x20)! = 0, then this is a generator function (generator functions).

CO = Cat.sayHi.func_code
Print Co.co_argcount # 1
Print Co.co_names # (' Name ',)
Print Co.co_varnames # (' Self ',)
Print Co.co_flags & 0b100 # 0

2.9. Stack frame (frame)

A stack frame represents a frame in a function call stack when the program runs. The function has no properties to fetch it because it is generated when the function is called, and the generator is returned by a function call, so there is a property pointing to the stack frame. To obtain a stack frame related to a function, it must be obtained when the function is called and the function has not been returned. You can get the current stack frame using the Sys module's _getframe () function, or the currentframe () function of the inspect module. The properties listed here are all read-only.

F_back: The previous frame of the call stack.
F_code: The code object corresponding to the stack frame.
F_locals: The same as the built-in function locals () when used on the current stack frame, but you can get the other frames first and then use this property to get the locals () of that frame.
F_globals: The same as the built-in function globals () when used on the current stack frame, but you can get other frames first ....

def add (x, Y=1):
f = inspect.currentframe ()
Print F.f_locals # Same as locals ()
Print F.f_back # <frame object at 0x...>

return x + y
Add (2)

2.10. Tracking (Traceback)
Tracing is the object used for backtracking when an exception occurs, as opposed to a stack frame. Because the exception is not built, and the exception is not captured will always be thrown to the outer stack frame, so you need to use a try to see this object. You can use the Sys module's exc_info () function to get it, which returns a tuple with elements that are exception type, exception object, and trace. The properties of the Traceback are all read-only.

Tb_next: The next tracked object to be traced.
Tb_frame: The corresponding stack frame is currently traced.
Tb_lineno: The line number of the current trace.

def div (x, y):
Try:
return x/Y
Except
TB = Sys.exc_info () [2] # return (Exc_type, Exc_value, Traceback)
Print TB
Print Tb.tb_lineno # "return x/Y" line number

Div (1, 0)

3. Using the Inspect module
The inspect module provides a series of functions to help use introspection. Here are just a few of the more commonly used functions to get all of the function data to view the documentation for the inspect module.

3.1. Check the object type
Is{module|class|function|method|builtin} (OBJ): Checks whether the object is a module, class, function, method, built-in function, or method.
Isroutine (obj): A callable type used to check whether an object is a function, method, built-in function, or method, and so on. This method is more convenient than multiple is* (), but its implementation still uses multiple is* ().

im = Cat.sayhi
if Inspect.isroutine (IM):
Im ()

For a class instance that implements __CALL__, this method returns FALSE. If the purpose is to be true as long as it can be called directly, use Isinstance (obj, collections). Callable) in this form. I do not know why callable in the collections module, sorry! I probably because the collections module contains a lot of other ABC (Abstract Base Class) because of it:)

3.2. Get object Information
GetMembers (object[, predicate]):   This method is an extended version of Dir (), which returns the property of the name found by Dir (), in the form of [(name, value), ...]。 In addition, predicate is a reference to a method,                   If specified, you should accept value as a parameter and return a Boolean value. If False, the corresponding property will not be returned. Use is* as the second parameter to filter out properties of the specified type.
GetModule (object):   Is it regrettable that the __module__ property in section 2nd returns only strings? This method is sure to satisfy you, which returns the module object where the definition of object is located.
Get{file|sourcefile} (object):   Gets the file name of the module that contains the definition of object | The source code file name (none if not);                                    ,         &NB Sp                          ,         &NB Sp                  The TypeError exception is thrown on built-in objects (built-in modules, classes, functions, methods).

Get{source|sourcelines} (Object): Gets the source code for the definition of object, returned as a string | string list.                                                                           The IOError exception is thrown when the code is unreachable. Can only be used with Module/class/function/method/code/frame/traceack objects.
Getargspec (func): Used only for methods, get parameters for method declarations, return tuples, respectively (list of common parameter names, * parameter name, * * Parameter name, default value tuple).                             If there is no value, it will be an empty list and 3 none. In the case of more than 2.6, a named tuple (Named Tuple) is returned, that is, the element in the tuple can be accessed in addition to the index by using the property name.
Getargvalues (frame): For the stack frame only, get the parameter value of the function call saved in the stack frame, return the tuple, respectively (a list of common parameter names, * parameter name, * * Parameter name, locals () of the frame). In the case of more than 2.6, a named tuple (Named Tuple) is returned, that is, the element in the tuple can be accessed in addition to the index by using the property name.
Getcallargs (func[, *args][, **kwds]): Returns a dictionary of values that correspond to the parameters of the method when invoked with args and Kwds. This method is only available in version 2.7.
GETMRO (CLS): Returns a type tuple that is followed by the order of the tuple when it looks for the class attribute.                                                                                               If it is a new class, it is the same as the cls.__mro__ result. But the old class does not __mro__ this property, the direct use of this property will report the exception, so this method still has its value. Returns the current stack frame object.

Other operation of the frame and traceback function please consult the inspect module's documentation, with less, here is not more introduction.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.