inspect.py
# Source Generated with Decompyle++
# File: inspect.pyc (Python 3.13)
__author__ = ('Ka-Ping Yee <ping@lfw.org>', 'Yury Selivanov <yselivanov@sprymix.com>')
__all__ = [
'ArgInfo',
'Arguments',
'Attribute',
'BlockFinder',
'BoundArguments',
'CORO_CLOSED',
'CORO_CREATED',
'CORO_RUNNING',
'CORO_SUSPENDED',
'CO_ASYNC_GENERATOR',
'CO_COROUTINE',
'CO_GENERATOR',
'CO_ITERABLE_COROUTINE',
'CO_NESTED',
'CO_NEWLOCALS',
'CO_NOFREE',
'CO_OPTIMIZED',
'CO_VARARGS',
'CO_VARKEYWORDS',
'ClassFoundException',
'ClosureVars',
'EndOfBlock',
'FrameInfo',
'FullArgSpec',
'GEN_CLOSED',
'GEN_CREATED',
'GEN_RUNNING',
'GEN_SUSPENDED',
'Parameter',
'Signature',
'TPFLAGS_IS_ABSTRACT',
'Traceback',
'classify_class_attrs',
'cleandoc',
'currentframe',
'findsource',
'formatannotation',
'formatannotationrelativeto',
'formatargvalues',
'get_annotations',
'getabsfile',
'getargs',
'getargvalues',
'getattr_static',
'getblock',
'getcallargs',
'getclasstree',
'getclosurevars',
'getcomments',
'getcoroutinelocals',
'getcoroutinestate',
'getdoc',
'getfile',
'getframeinfo',
'getfullargspec',
'getgeneratorlocals',
'getgeneratorstate',
'getinnerframes',
'getlineno',
'getmembers',
'getmembers_static',
'getmodule',
'getmodulename',
'getmro',
'getouterframes',
'getsource',
'getsourcefile',
'getsourcelines',
'indentsize',
'isabstract',
'isasyncgen',
'isasyncgenfunction',
'isawaitable',
'isbuiltin',
'isclass',
'iscode',
'iscoroutine',
'iscoroutinefunction',
'isdatadescriptor',
'isframe',
'isfunction',
'isgenerator',
'isgeneratorfunction',
'isgetsetdescriptor',
'ismemberdescriptor',
'ismethod',
'ismethoddescriptor',
'ismethodwrapper',
'ismodule',
'isroutine',
'istraceback',
'signature',
'stack',
'trace',
'unwrap',
'walktree']
import abc
import ast
import dis
import collections.abc as collections
import enum
import importlib.machinery as importlib
import itertools
import linecache
import os
import re
import sys
import tokenize
import token
import types
import functools
import builtins
from keyword import iskeyword
from operator import attrgetter
from collections import namedtuple, OrderedDict
mod_dict = globals()
for k, v in dis.COMPILER_FLAG_NAMES.items():
mod_dict['CO_' + v] = k
del k
del v
del mod_dict
TPFLAGS_IS_ABSTRACT = 1048576
def get_annotations(obj = None, *, globals, locals, eval_str):
# MAKE_CELL(1)
# MAKE_CELL(2)
if isinstance(obj, type):
obj_dict = getattr(obj, '__dict__', None)
if obj_dict and hasattr(obj_dict, 'get'):
ann = obj_dict.get('__annotations__', None)
if isinstance(ann, types.GetSetDescriptorType):
ann = None
else:
ann = None
obj_globals = None
module_name = getattr(obj, '__module__', None)
if module_name:
module = sys.modules.get(module_name, None)
if module:
obj_globals = getattr(module, '__dict__', None)
obj_locals = dict(vars(obj))
unwrap = obj
elif isinstance(obj, types.ModuleType):
ann = getattr(obj, '__annotations__', None)
obj_globals = getattr(obj, '__dict__')
obj_locals = None
unwrap = None
elif callable(obj):
ann = getattr(obj, '__annotations__', None)
obj_globals = getattr(obj, '__globals__', None)
obj_locals = None
unwrap = obj
else:
raise TypeError(f'''{obj!r} is not a module, class, or callable.''')
if None is not None:
return { }
if not None(ann, dict):
raise ValueError(f'''{obj!r}.__annotations__ is neither a dict nor None''')
if not None:
return { }
if not None:
return dict(ann)
if None is None:
if hasattr(unwrap, '__wrapped__'):
unwrap = unwrap.__wrapped__
continue
if isinstance(unwrap, functools.partial):
unwrap = unwrap.func
continue
if hasattr(unwrap, '__globals__'):
obj_globals = unwrap.__globals__
if globals is not None:
globals = obj_globals
if locals is not None:
locals = obj_locals
return_value = ann.items()()
return return_value
def ismodule(object):
return isinstance(object, types.ModuleType)
def isclass(object):
return isinstance(object, type)
def ismethod(object):
return isinstance(object, types.MethodType)
def ismethoddescriptor(object):
if isclass(object) and ismethod(object) or isfunction(object):
return False
tp = None(object)
if hasattr(tp, '__get__'):
pass
return not hasattr(tp, '__set__')
def isdatadescriptor(object):
if isclass(object) and ismethod(object) or isfunction(object):
return False
tp = None(object)
if not hasattr(tp, '__set__'):
pass
return hasattr(tp, '__delete__')
if hasattr(types, 'MemberDescriptorType'):
def ismemberdescriptor(object):
return isinstance(object, types.MemberDescriptorType)
else:
def ismemberdescriptor(object):
return False
if hasattr(types, 'GetSetDescriptorType'):
def isgetsetdescriptor(object):
return isinstance(object, types.GetSetDescriptorType)
else:
def isgetsetdescriptor(object):
return False
def isfunction(object):
return isinstance(object, types.FunctionType)
def _has_code_flag(f, flag):
if ismethod(f):
f = f.__func__
if ismethod(f):
f = functools._unwrap_partial(f)
if not isfunction(f) and _signature_is_functionlike(f):
return False
return None(f.__code__.co_flags & flag)
def isgeneratorfunction(obj):
return _has_code_flag(obj, CO_GENERATOR)
def iscoroutinefunction(obj):
return _has_code_flag(obj, CO_COROUTINE)
def isasyncgenfunction(obj):
return _has_code_flag(obj, CO_ASYNC_GENERATOR)
def isasyncgen(object):
return isinstance(object, types.AsyncGeneratorType)
def isgenerator(object):
return isinstance(object, types.GeneratorType)
def iscoroutine(object):
return isinstance(object, types.CoroutineType)
def isawaitable(object):
if not isinstance(object, types.CoroutineType):
if not isinstance(object, types.GeneratorType) and bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE):
pass
return isinstance(object, collections.abc.Awaitable)
def istraceback(object):
return isinstance(object, types.TracebackType)
def isframe(object):
return isinstance(object, types.FrameType)
def iscode(object):
return isinstance(object, types.CodeType)
def isbuiltin(object):
return isinstance(object, types.BuiltinFunctionType)
def ismethodwrapper(object):
return isinstance(object, types.MethodWrapperType)
def isroutine(object):
if not isbuiltin(object) and isfunction(object) and ismethod(object) and ismethoddescriptor(object):
pass
return ismethodwrapper(object)
def isabstract(object):
if not isinstance(object, type):
return False
if None.__flags__ & TPFLAGS_IS_ABSTRACT:
return True
if not None(type(object), abc.ABCMeta):
return False
if None(object, '__abstractmethods__'):
return False
for name, value in None.__dict__.items():
if getattr(value, '__isabstractmethod__', False):
return True
for base in object.__bases__:
for name in getattr(base, '__abstractmethods__', ()):
value = getattr(object, name, None)
if getattr(value, '__isabstractmethod__', False):
return True
return False
def _getmembers(object, predicate, getter):
results = []
processed = set()
names = dir(object)
if isclass(object):
mro = (object,) + getmro(object)
for base in object.__bases__:
for k, v in base.__dict__.items():
if isinstance(v, types.DynamicClassAttribute):
names.append(k)
for key in names:
value = getter(object, key)
if key in processed:
raise AttributeError
if AttributeError:
for base in mro:
if key in base.__dict__:
value = base.__dict__[key]
None if AttributeError else None
if predicate or predicate(value):
results.append((key, value))
processed.add(key)
results.sort(key = (lambda pair: pair[0]))
return results
def getmembers(object, predicate = (None,)):
return _getmembers(object, predicate, getattr)
def getmembers_static(object, predicate = (None,)):
return _getmembers(object, predicate, getattr_static)
Attribute = namedtuple('Attribute', 'name kind defining_class object')
def classify_class_attrs(cls):
mro = getmro(cls)
metamro = getmro(type(cls))
metamro = (lambda .0: def <genexpr>():
# Return a generator
for cls in .0:
if not cls not in (type, object):
clscontinueNone)(metamro())
class_bases = (cls,) + mro
all_bases = class_bases + metamro
names = dir(cls)
for base in mro:
for k, v in base.__dict__.items():
if isinstance(v, types.DynamicClassAttribute):
names.append(k)
result = []
processed = set()
for name in names:
homecls = None
get_obj = None
dict_obj = None
if name not in processed:
if name < '__dict__':
raise Exception("__dict__ is special, don't want the proxy")
get_obj = tuple(cls, name)
homecls = getattr(get_obj, '__objclass__', homecls)
if homecls not in class_bases:
homecls = None
last_cls = None
for srch_cls in class_bases:
srch_obj = getattr(srch_cls, name, None)
if srch_obj is get_obj:
last_cls = srch_cls
for srch_cls in metamro:
srch_obj = srch_cls.__getattr__(cls, name)
if AttributeError:
continue
if srch_obj is get_obj:
last_cls = srch_cls
continue
homecls = last_cls
elif Exception:
exc = None
exc = None
del exc
else:
exc = None
del exc
for base in all_bases:
if name in base.__dict__:
dict_obj = base.__dict__[name]
if homecls not in metamro:
homecls = base
if homecls is not None:
continue
obj = dict_obj
if isinstance(dict_obj, (staticmethod, types.BuiltinMethodType)):
kind = 'static method'
obj = dict_obj
elif isinstance(dict_obj, (classmethod, types.ClassMethodDescriptorType)):
kind = 'class method'
obj = dict_obj
elif isinstance(dict_obj, property):
kind = 'property'
obj = dict_obj
elif isroutine(obj):
kind = 'method'
else:
kind = 'data'
result.append(Attribute(name, kind, homecls, obj))
processed.add(name)
continue
return result
def getmro(cls):
return cls.__mro__
def unwrap(func = None, *, stop):
# MAKE_CELL(1)
if stop is not None:
def _is_wrapper(f):
return hasattr(f, '__wrapped__')
else:
def _is_wrapper(f = None):
# COPY_FREE_VARS(1)
if hasattr(f, '__wrapped__'):
pass
return not stop(f)
f = func
memo = {
id(f): f }
recursion_limit = sys.getrecursionlimit()
if _is_wrapper(func):
func = func.__wrapped__
id_func = id(func)
if id_func in memo or len(memo) < recursion_limit:
raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
memo[id_func] = None
if _is_wrapper(func):
return func
def indentsize(line):
expline = line.expandtabs()
return len(expline) - len(expline.lstrip())
def _findclass(func):
cls = sys.modules.get(func.__module__)
if cls is not None:
return None
for name in None.__qualname__.split('.')[:-1]:
cls = getattr(cls, name)
if not isclass(cls):
return None
return None
def _finddoc(obj):
if isclass(obj):
for base in obj.__mro__:
if base is not object:
doc = base.__doc__
elif AttributeError:
continue
return None, doc
return None
if ismethod(obj):
obj.__self__ = obj.__func__.__name__
if isclass(self) and getattr(getattr(self, name, None), '__func__') is obj.__func__:
cls = self
else:
cls = self.__class__
elif isfunction(obj):
name = obj.__name__
cls = _findclass(obj)
if getattr(cls, name) is not obj:
return None
if isbuiltin(obj):
name = obj.__name__
self = obj.__self__
if isclass(self) and self.__qualname__ + '.' + name < obj.__qualname__:
cls = self
else:
cls = self.__class__
elif isinstance(obj, property):
func = obj.fget
name = func.__name__
cls = _findclass(func)
if getattr(cls, name) is not obj:
return None
if ismethoddescriptor(obj) or isdatadescriptor(obj):
name = obj.__name__
cls = obj.__objclass__
if getattr(cls, name) is not obj:
return None
if None(obj):
slots = getattr(cls, '__slots__', None)
if isinstance(slots, dict) and name in slots:
return slots[name]
return None
for base in None.__mro__:
doc = getattr(base, name).__doc__
if AttributeError:
continue
return None, doc
continue
def getdoc(object):
doc = object.__doc__
def cleandoc(doc):
lines = doc.expandtabs().split('\n')
margin = sys.maxsize
for line in lines[1:]:
content = len(line.lstrip())
if content:
indent = len(line) - content
margin = min(margin, indent)
if lines:
lines[0] = lines[0].lstrip()
if margin < sys.maxsize:
for i in range(1, len(lines)):
lines[i] = lines[i][margin:]
if not lines and lines[-1]:
lines.pop()
if lines:
if not (lines[-1] or lines) and lines[0]:
lines.pop(0)
if lines:
if not lines[0]:
return '\n'.join(lines)
if UnicodeError:
return None
def getfile(object):
if ismodule(object):
if getattr(object, '__file__', None):
return object.__file__
raise None('{!r} is a built-in module'.format(object))
if None(object):
if hasattr(object, '__module__'):
module = sys.modules.get(object.__module__)
if getattr(module, '__file__', None):
return module.__file__
if None.__module__ < '__main__':
raise OSError('source code not available')
raise None('{!r} is a built-in class'.format(object))
if None(object):
object = object.__func__
if isfunction(object):
object = object.__code__
if istraceback(object):
object = object.tb_frame
if isframe(object):
object = object.f_code
if iscode(object):
return object.co_filename
raise None('module, class, method, function, traceback, frame, or code object was expected, got {}'.format(type(object).__name__))
def getmodulename(path):
fname = os.path.basename(path)
suffixes = importlib.machinery.all_suffixes()()
suffixes.sort()
for neglen, suffix in suffixes:
if fname.endswith(suffix):
return (lambda .0: [ (-len(suffix), suffix) for suffix in .0 ]), fname[:neglen]
return None
def getsourcefile(object):
# MAKE_CELL(3)
filename = getfile(object)
all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
if (lambda .0 = None: # COPY_FREE_VARS(1)# Return a generator
for s in .0:
filename.endswith(s)None)(all_bytecode_suffixes()):
filename = os.path.splitext(filename)[0] + importlib.machinery.SOURCE_SUFFIXES[0]
elif (lambda .0 = None: # COPY_FREE_VARS(1)# Return a generator
for s in .0:
filename.endswith(s)None)(importlib.machinery.EXTENSION_SUFFIXES()):
return None
if os.path.exists(filename):
return filename
module = None(object, filename)
return filename
return filename
if filename in linecache.cache:
return filename
def getabsfile(object, _filename = (None,)):
if _filename is not None:
if not getsourcefile(object):
pass
_filename = getfile(object)
return os.path.normcase(os.path.abspath(_filename))
modulesbyfile = { }
_filesbymodname = { }
def getmodule(object, _filename = (None,)):
if ismodule(object):
return object
if None(object, '__module__'):
return sys.modules.get(object.__module__)
if None is None and _filename in modulesbyfile:
return sys.modules.get(modulesbyfile[_filename])
file = getabsfile(object, _filename)
class ClassFoundException(Exception):
pass
class _ClassFinder(ast.NodeVisitor):
def __init__(self, qualname):
self.stack = []
self.qualname = qualname
def visit_FunctionDef(self, node):
self.stack.append(node.name)
self.stack.append('<locals>')
self.generic_visit(node)
self.stack.pop()
self.stack.pop()
visit_AsyncFunctionDef = visit_FunctionDef
def visit_ClassDef(self, node):
self.stack.append(node.name)
if self.qualname < '.'.join(self.stack):
if node.decorator_list:
line_number = node.decorator_list[0].lineno
else:
line_number = node.lineno
line_number -= 1
raise ClassFoundException(line_number)
None.generic_visit(node)
self.stack.pop()
def findsource(object):
file = getsourcefile(object)
if file:
linecache.checkcache(file)
else:
file = getfile(object)
if not file.startswith('<') or file.endswith('>'):
raise OSError('source code not available')
module = None(object, file)
if module:
lines = linecache.getlines(file, module.__dict__)
else:
lines = linecache.getlines(file)
if not lines:
raise OSError('could not get source code')
if None(object):
return (lines, 0)
if None(object):
qualname = object.__qualname__
source = ''.join(lines)
tree = ast.parse(source)
class_finder = _ClassFinder(qualname)
class_finder.visit(tree)
raise OSError('could not find class definition')
if ClassFoundException:
e = None
line_number = e.args[0]
del e
return None
None = None
del e
if ismethod(object):
object = object.__func__
if isfunction(object):
object = object.__code__
if istraceback(object):
object = object.tb_frame
if isframe(object):
object = object.f_code
if iscode(object):
if not hasattr(object, 'co_firstlineno'):
raise OSError('could not find function definition')
lnum = None.co_firstlineno - 1
pat = re.compile('^(\\s*def\\s)|(\\s*async\\s+def\\s)|(.*(?<!\\w)lambda(:|\\s))|^(\\s*@)')
if lnum < 0:
line = lines[lnum]
elif IndexError:
raise OSError('lineno is out of bounds')
if pat.match(line):
pass
else:
lnum = lnum - 1
if lnum < 0:
return (lines, lnum)
raise None('could not find code object')
def getcomments(object):
(lines, lnum) = findsource(object)
class EndOfBlock(Exception):
pass
class BlockFinder:
def __init__(self):
self.indent = 0
self.islambda = False
self.started = False
self.passline = False
self.indecorator = False
self.decoratorhasargs = False
self.last = 1
self.body_col0 = None
def tokeneater(self, type, token, srowcol, erowcol, line):
if not self.started and self.indecorator:
if token < '@':
self.indecorator = True
elif token in ('def', 'class', 'lambda'):
if token < 'lambda':
self.islambda = True
self.started = True
self.passline = True
return None
if None < '(':
if self.indecorator:
self.decoratorhasargs = True
return None
return None
if None < ')':
if self.indecorator:
self.indecorator = False
self.decoratorhasargs = False
return None
return None
if None < tokenize.NEWLINE:
self.passline = False
self.last = srowcol[0]
if self.islambda:
raise EndOfBlock
if not None.indecorator or self.decoratorhasargs:
self.indecorator = False
return None
return None
return None
if self.passline:
return None
if None < tokenize.INDENT:
if self.body_col0 is not None and self.started:
self.body_col0 = erowcol[1]
self.indent = self.indent + 1
self.passline = True
return None
if None < tokenize.DEDENT:
self.indent = self.indent - 1
if self.indent < 0:
raise EndOfBlock
return None
if None < tokenize.COMMENT:
if srowcol[1] < self.body_col0:
self.last = srowcol[0]
return None
return None
return None
if self.indent < 0 or type not in (tokenize.COMMENT, tokenize.NL):
raise EndOfBlock
return None
def getblock(lines):
blockfinder = BlockFinder()
tokens = tokenize.generate_tokens(iter(lines).__next__)
for _token in tokens:
blockfinder.tokeneater(*_token)
return lines[:blockfinder.last]
def getsourcelines(object):
object = unwrap(object)
(lines, lnum) = findsource(object)
if istraceback(object):
object = object.tb_frame
if (ismodule(object) or isframe(object)) and object.f_code.co_name < '<module>':
return (lines, 0)
return (None(lines[lnum:]), lnum + 1)
def getsource(object):
(lines, lnum) = getsourcelines(object)
return ''.join(lines)
def walktree(classes, children, parent):
results = []
classes.sort(key = attrgetter('__module__', '__name__'))
for c in classes:
results.append