Specific usage of Python standard library inspect

  • 2020-06-15 09:19:40
  • OfStack

inspect module is used to collect python object information, you can get the class or function parameter information, source code, parsing stack, object type check, and so on, there are several useful methods:

Doc: Here it is

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.

This module provides useful methods for objects such as modules, classes, methods, functions, etc.

getargspec(func)

Returns 1 named tuple ArgSpect(args, varargs, keywords, defaults), where args is the function position parameter list, varargs is the * parameter name, keywords is the ** parameter name, and defaults is the default parameter value tuple.

In the practice of automatically initialing the instance properties with the argument of ___ 28EN__, get the function's position argument name with 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 will not apply if the method of init__ receives any number of keyword arguments using the ** special argument. It is possible to use the co_flags attribute of bytecode to determine if the ** parameter exists.

When the function USES *args syntax to accept any number of position arguments, co_flags sets to 0x04, when **kwargs syntax sets to 0x08, when the function is a generator, sets to 0x2000, and the other bits remain:


>>> def foo(x, *args, **kwargv):
  pass
>>> foo.__code__.co_varnames
('x', 'args', 'kwargv')
>>> foo.__code__.co_flags & 0x04
4
>>> foo.__code__.co_flags & 0x08
8

The getargspec() method of the inspect module USES this judgment to obtain special parameters of the function. Per ___, you can easily get the ** of each ___ 51EN__ :


import inspect
def 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 was properly initialized.

getmembers(object[, predicate])

Returns 1 list containing all the members of the object (name, value). The return contains more than the object's ___ (65en__) and the source code is achieved with dir().

predicate is an optional function argument. Members judged by this function as True are returned.

getmodule(object)

Returns the module that defines the object

getsource(object)

Returns the source code of the object

getsourcelines(object)

Returns 1 tuple, item 1 is the list of source code rows for the object, and item 2 is the line number of source code for line 1

ismodule,isclass,ismethod,isfunction,isbuiltin

Most of the methods for determining object types are functions that wrap statements like isinstance(object, ES93en.FunctionType).

Now you can use type determination to return a method of a class:


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

Related articles: