Python standard library inspect, python standard inspect

Source: Internet
Author: User

Python standard library inspect, python standard inspect

The inspect module is used to collect python object information and obtain the parameter information of the class or function, the source code, the Parsing Stack, And the type check of the object. There are several useful methods:

Getargspec (func)

Returns an ArgSpect (args, varargs, keywords, defaults) name. args is a list of Function Location Parameter names, varargs is a * parameter name, and keywords is a ** parameter name, ults is the tuples of default parameter values.

In the practice of using the _ init _ parameter to automatically initialize instance attributes, the location parameter name of the function is obtained using the co_varnames attribute of the bytecode object:

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 ** special parameters to receive any number of keyword parameters. The feasible method is to use the co_flags attribute of the bytecode to determine whether the ** parameter exists.

When the function uses the * args syntax to accept any number of location parameters, co_flags is set to 0x04. When the ** kwargs syntax is used, it is set to 0x08. When the function is a generator, positions 0x2000, other bits are retained:

>>> 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 uses this judgment to obtain the special parameters of the function. Now you can easily 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__

Result:

{'color': 'yellow', 'num': 1, 'name': 'bar'}

The object has been correctly initialized.

Getmembers (object [, predicate])

Returns the (name, value) list of all members of an object. The returned content is more than the content contained in the object _ dict _. The source code is implemented through dir.

Predicate is an optional function parameter. Only True members of this function are returned.

Getmodule (object)

Return the module of the defined object

Getsource (object)

Source code of the returned object

Getsourcelines (object)

Returns a tuples. The first entry of the tuples is the list of source code lines of the object, and the second entry is the source code line number of the first line.

Ismodule, isclass, ismethod, isfunction, isbuiltin

A series of methods for determining object types are mostly functions that encapsulate statements such as isinstance (object, types. FunctionType.

Now we can use the type judgment to return the method of a class:

class Foo(object):    '''Foo doc'''    def __init__(self, name):        self.__name = name    def getname(self):        return self.__nameinspect.getmembers(Foo, inspect.ismethod)

  

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