python inspect 模块 和 types 模块 判断是否是方法,模块,函数等内置特殊属性

时间:2022-11-02 16:13:27

python inspect 模块 和 types 模块 判断是否是方法,模块,函数等内置特殊属性

inspect

import inspect

def fun():

    pass

inspect.ismodule(fun)

inspect.isclass(fun)

inspect.ismethod(fun)

for attr in dir(inspect):

    print(attr)

输出:

isabstract
isasyncgen
isasyncgenfunction
isawaitable
isbuiltin
isclass
iscode
iscoroutine
iscoroutinefunction
isdatadescriptor
isframe
isfunction
isgenerator
isgeneratorfunction
isgetsetdescriptor
ismemberdescriptor
ismethod
ismethoddescriptor
ismodule
isroutine
istraceback
itertools

...

types

import types

def fun():

    pass

isinstance(fun, types.FunctionType)

for t in dir(types):

    print(t)

输出:

AsyncGeneratorType
BuiltinFunctionType
BuiltinMethodType
ClassMethodDescriptorType
CodeType
CoroutineType
DynamicClassAttribute
FrameType
FunctionType
GeneratorType
GetSetDescriptorType
LambdaType
MappingProxyType
MemberDescriptorType
MethodDescriptorType
MethodType
MethodWrapperType
ModuleType
SimpleNamespace
TracebackType
WrapperDescriptorType
...