Python Standard library Inspect

Source: Internet
Author: User

The inspect module collects information about Python objects, can get information about the parameters of a class or function, source code, parse the stack, type check objects, and so on, there are several useful methods:

Getargspec (func)

Returns a named tuple Argspect (args, varargs, keywords, defaults), args is the list of function positional parameter names, varargs is * parameter name, keywords is * * parameter name, defaults is a tuple of default parameter values.

In the practice of automatically initializing instance properties with the __init__ parameter, the Co_varnames attribute of the bytecode object is used to get the positional parameter name of the function:

def attr_from_locals (locals_dict): Self    = Locals_dict.pop ("self")    code = self.__init__.__func__.__code__    args = Code.co_varnames[1:code.co_argcount] for    K in args:        setattr (self, k, locals_dict[k])         class Foo (object):    def __init__ (self, name, color, num=1):        x = 1        attr_from_locals (Locals ())

The above code is not applicable when the __init__ method uses the * * Special parameter to receive any number of keyword parameters. The possible approach is to use the Co_flags attribute of the bytecode to determine if the * * parameter exists.

When the function uses the *args syntax to accept any number of positional arguments, the co_flags resets the 0x04, when using **kwargs syntax, the set bit 0x08, the function is a generator, the position is 0x2000, the other bits are reserved:

>>> def foo (x, *args, **KWARGV):    pass>>> foo.__code__.co_varnames (' x ', ' args ', ' kwargv ') > >> Foo.__code__.co_flags & 0x044>>> Foo.__code__.co_flags & 0x088

The Getargspec () method of the inspect module is precisely used to obtain the special parameters of the function. It is now convenient to get the * * Parameters of __init__:

Import Inspectdef attr_from_locals (locals_dict): Self    = Locals_dict.pop ("self")    args = Inspect.getargspec ( self.__init__.__func__). Args[1:] for    K in args:        setattr (self, k, locals_dict[k])    keywords = Inspect.getargspec (self.__init__.__func__). Keywords    if keywords:        keywords_dict = locals_dict[keywords] For        K in keywords_dict:            setattr (self, k, keywords_dict[k])       class Foo (object):    def __init__ (self, Name, **KWARGV):        attr_from_locals (Locals ()) F = Foo (' Bar ', color= ' yellow ', num=1) print f.__dict__

The result is:

{' Color ': ' Yellow ', ' num ': 1, ' name ': ' Bar '}

The object has been initialized correctly.

GetMembers (object[, predicate])

Returns a list of (name, value) that contains all the members of the object. The content returned is more than the object's __dict__ contains, and the source code is implemented through DIR ().

predicate is an optional function parameter that is returned by a member that is judged to be true by this function.

GetModule (object)

Returns the module that defines the object

GetSource (object)

Returns the source code of an object

Getsourcelines (object)

Returns a tuple, the first item of a tuple is the list of object source lines, and the second is the line number of the first line of source code


A series of methods for judging object types are mostly packaged with Isinstance (object, types. Functiontype) functions such as statements.

You can now return a method of a class with type judgment:

Class Foo (object):    ' foo Doc '    def __init__ (self, name):        self.__name = name    def getname (self):        return Self.__nameinspect.getmembers (Foo, Inspect.ismethod)


Python Standard library Inspect

Related Article

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