本文整理汇总了Python中inspect.getargvalues方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.getargvalues方法的具体用法?Python inspect.getargvalues怎么用?Python inspect.getargvalues使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.getargvalues方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: detect_scopes
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def detect_scopes():
scopes = []
current_frame = inspect.currentframe()
while current_frame is not None:
if current_frame.f_code.co_name == 'logging_scope':
scopes.append(current_frame.f_locals['name'])
else:
argvalues = inspect.getargvalues(current_frame)
if 'self' in argvalues.args and getattr(argvalues.locals['self'].__class__, 'AUTO_LOGGING_SCOPE',
False):
scopes.append(argvalues.locals['self'])
current_frame = current_frame.f_back
out_scopes = []
seen = set()
for scope in scopes[::-1]:
if scope not in seen:
out_scopes.append(
scope
if isinstance(scope, six.string_types) else
(getattr(scope, "LOGGING_SCOPE", None) or getattr(scope, "name", None) or scope.__class__.__name__))
seen.add(scope)
return out_scopes
示例2: super_patchy
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def super_patchy(*args, do_call=True, **kwargs):
""" super() for patches!
When called from within a patched in function will return or call the
function that it replaced, preserving self/cls arguments
"""
caller_frame = inspect.currentframe().f_back
caller = inspect.getargvalues(caller_frame)
old_func = patchy_records[caller_frame.f_code]
if caller.args[0] in ['self', 'cls']:
# If caller has the appearance of being bound (to instance or class)
old_func = MethodType(old_func, caller.locals[caller.args[0]])
if do_call:
return old_func(*args, **kwargs)
return old_func
示例3: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def __init__(self, grid_num: int, bounds, bond_struc: Structure,
svd_rank=0, mean_only: bool=False, n_cpus: int=None,
n_sample: int=100):
'''
Build 2-body MGP
bond_struc: Mock structure used to sample 2-body forces on 2 atoms
'''
self.grid_num = grid_num
self.bounds = bounds
self.bond_struc = bond_struc
self.svd_rank = svd_rank
self.mean_only = mean_only
self.n_cpus = n_cpus
self.n_sample = n_sample
spc = bond_struc.coded_species
self.species_code = Z_to_element(spc[0]) + '_' + Z_to_element(spc[1])
# arg_dict = inspect.getargvalues(inspect.currentframe())[3]
# del arg_dict['self']
# self.__dict__.update(arg_dict)
self.build_map_container()
示例4: get_init_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def get_init_args(frame) -> dict:
_, _, _, local_vars = inspect.getargvalues(frame)
if '__class__' not in local_vars:
return
cls = local_vars['__class__']
spec = inspect.getfullargspec(cls.__init__)
init_parameters = inspect.signature(cls.__init__).parameters
self_identifier = spec.args[0] # "self" unless user renames it (always first arg)
varargs_identifier = spec.varargs # by convention this is named "*args"
kwargs_identifier = spec.varkw # by convention this is named "**kwargs"
exclude_argnames = (
varargs_identifier, kwargs_identifier, self_identifier, '__class__', 'frame', 'frame_args'
)
# only collect variables that appear in the signature
local_args = {k: local_vars[k] for k in init_parameters.keys()}
local_args.update(local_args.get(kwargs_identifier, {}))
local_args = {k: v for k, v in local_args.items() if k not in exclude_argnames}
return local_args
示例5: collect_init_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def collect_init_args(frame, path_args: list, inside: bool = False) -> list:
"""
Recursively collects the arguments passed to the child constructors in the inheritance tree.
Args:
frame: the current stack frame
path_args: a list of dictionaries containing the constructor args in all parent classes
inside: track if we are inside inheritance path, avoid terminating too soon
Return:
A list of dictionaries where each dictionary contains the arguments passed to the
constructor at that level. The last entry corresponds to the constructor call of the
most specific class in the hierarchy.
"""
_, _, _, local_vars = inspect.getargvalues(frame)
if '__class__' in local_vars:
local_args = get_init_args(frame)
# recursive update
path_args.append(local_args)
return collect_init_args(frame.f_back, path_args, inside=True)
elif not inside:
return collect_init_args(frame.f_back, path_args, inside)
else:
return path_args
示例6: get_caller_locals
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def get_caller_locals(decorators=0):
'''returns the locals of the calling function.
from http://pylab.blogspot.com/2009/02/
python-accessing-caller-locals-from.html
Arguments
---------
decorators : int
Number of contexts to go up to reach calling function
of interest.
Returns
-------
locals : dict
Dictionary of variable defined in the context of the
calling function.
'''
f = sys._getframe(2 + decorators)
args = inspect.getargvalues(f)
return args[3]
示例7: extract_ast_stack
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def extract_ast_stack(frames):
ast_stack = []
ast_seen = []
for frame in frames:
ast_frame = []
a = inspect.getargvalues(frame[0])
def tryget(x,a=a):
try:
return a.locals.get(x)
except (TypeError, KeyError):
pass
args = map(tryget, a.args)
if a.varargs:
args.extend(a.locals[a.varargs])
if a.keywords:
args.extend(v for k,v in sorted(a.locals[a.keywords].items()))
for arg in args:
if isinstance(arg, AST) and arg not in ast_seen:
ast_seen.append(arg)
ast_frame.append(arg)
if ast_frame:
ast_stack.append(ast_frame)
return ast_stack
示例8: read_json
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def read_json(
path_or_buf=None,
orient=None,
typ="frame",
dtype=None,
convert_axes=None,
convert_dates=True,
keep_default_dates=True,
numpy=False,
precise_float=False,
date_unit=None,
encoding=None,
lines=False,
chunksize=None,
compression="infer",
):
_, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
from modin.data_management.dispatcher import EngineDispatcher
return DataFrame(query_compiler=EngineDispatcher.read_json(**kwargs))
示例9: read_gbq
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def read_gbq(
query: str,
project_id: Optional[str] = None,
index_col: Optional[str] = None,
col_order: Optional[List[str]] = None,
reauth: bool = False,
auth_local_webserver: bool = False,
dialect: Optional[str] = None,
location: Optional[str] = None,
configuration: Optional[Dict[str, Any]] = None,
credentials=None,
use_bqstorage_api: Optional[bool] = None,
private_key=None,
verbose=None,
progress_bar_type: Optional[str] = None,
) -> DataFrame:
_, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
kwargs.update(kwargs.pop("kwargs", {}))
from modin.data_management.dispatcher import EngineDispatcher
return DataFrame(query_compiler=EngineDispatcher.read_gbq(**kwargs))
示例10: read_html
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def read_html(
io,
match=".+",
flavor=None,
header=None,
index_col=None,
skiprows=None,
attrs=None,
parse_dates=False,
thousands=",",
encoding=None,
decimal=".",
converters=None,
na_values=None,
keep_default_na=True,
displayed_only=True,
):
_, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
from modin.data_management.dispatcher import EngineDispatcher
return DataFrame(query_compiler=EngineDispatcher.read_html(**kwargs))
示例11: read_hdf
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def read_hdf(
path_or_buf,
key=None,
mode: str = "r",
errors: str = "strict",
where=None,
start: Optional[int] = None,
stop: Optional[int] = None,
columns=None,
iterator=False,
chunksize: Optional[int] = None,
**kwargs,
):
_, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
kwargs.update(kwargs.pop("kwargs", {}))
from modin.data_management.dispatcher import EngineDispatcher
return DataFrame(query_compiler=EngineDispatcher.read_hdf(**kwargs))
示例12: read_stata
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def read_stata(
filepath_or_buffer,
convert_dates=True,
convert_categoricals=True,
index_col=None,
convert_missing=False,
preserve_dtypes=True,
columns=None,
order_categoricals=True,
chunksize=None,
iterator=False,
):
_, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
from modin.data_management.dispatcher import EngineDispatcher
return DataFrame(query_compiler=EngineDispatcher.read_stata(**kwargs))
示例13: read_fwf
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def read_fwf(
filepath_or_buffer: Union[str, pathlib.Path, IO[AnyStr]],
colspecs="infer",
widths=None,
infer_nrows=100,
**kwds,
):
from modin.data_management.dispatcher import EngineDispatcher
_, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
kwargs.update(kwargs.pop("kwds", {}))
pd_obj = EngineDispatcher.read_fwf(**kwargs)
# When `read_fwf` returns a TextFileReader object for iterating through
if isinstance(pd_obj, pandas.io.parsers.TextFileReader):
reader = pd_obj.read
pd_obj.read = lambda *args, **kwargs: DataFrame(
query_compiler=reader(*args, **kwargs)
)
return pd_obj
return DataFrame(query_compiler=pd_obj)
示例14: dbg
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def dbg(log = ""):
"""Print a message if debugging is enabled"""
if DEBUG:
stackitem = inspect.stack()[1]
parent_frame = stackitem[0]
method = parent_frame.f_code.co_name
names, varargs, keywords, local_vars = inspect.getargvalues(parent_frame)
try:
self_name = names[0]
classname = local_vars[self_name].__class__.__name__
except IndexError:
classname = "noclass"
if DEBUGFILES:
line = stackitem[2]
filename = parent_frame.f_code.co_filename
extra = " (%s:%s)" % (filename, line)
else:
extra = ""
if DEBUGCLASSES != [] and classname not in DEBUGCLASSES:
return
if DEBUGMETHODS != [] and method not in DEBUGMETHODS:
return
try:
print >> sys.stderr, "%s::%s: %s%s" % (classname, method, log, extra)
except IOError:
pass
示例15: frameInfo
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getargvalues [as 别名]
def frameInfo(self, fr):
filename = fr.f_code.co_filename
funcname = fr.f_code.co_name
lineno = fr.f_lineno
callfr = sys._getframe(3)
callline = "%s %d" % (callfr.f_code.co_name, callfr.f_lineno)
args, _, _, value_dict = inspect.getargvalues(fr)
if len(args) and args[0] == 'self':
instance = value_dict.get('self', None)
if instance is not None:
cls = getattr(instance, '__class__', None)
if cls is not None:
funcname = cls.__name__ + "." + funcname
return "%s: %s %s: %s" % (callline, filename, lineno, funcname)