本文整理匯總了Python中inspect.getsource方法的典型用法代碼示例。如果您正苦於以下問題:Python inspect.getsource方法的具體用法?Python inspect.getsource怎麽用?Python inspect.getsource使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類inspect
的用法示例。
在下文中一共展示了inspect.getsource方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def __init__(self,
name=None, # Network name. Used to select TensorFlow name and variable scopes.
func=None, # Fully qualified name of the underlying network construction function.
**static_kwargs): # Keyword arguments to be passed in to the network construction function.
self._init_fields()
self.name = name
self.static_kwargs = dict(static_kwargs)
# Init build func.
module, self._build_func_name = import_module(func)
self._build_module_src = inspect.getsource(module)
self._build_func = find_obj_in_module(module, self._build_func_name)
# Init graph.
self._init_graph()
self.reset_vars()
示例2: _inferWaiter
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def _inferWaiter(gen):
f = gen.gi_frame
s = inspect.getsource(f)
s = _dedent(s)
root = ast.parse(s)
root.symdict = f.f_globals.copy()
root.symdict.update(f.f_locals)
# print ast.dump(root)
v = _YieldVisitor(root)
v.visit(root)
if v.kind == _kind.EDGE_TUPLE:
return _EdgeTupleWaiter(gen)
if v.kind == _kind.SIGNAL_TUPLE:
return _SignalTupleWaiter(gen)
if v.kind == _kind.DELAY:
return _DelayWaiter(gen)
if v.kind == _kind.EDGE:
return _EdgeWaiter(gen)
if v.kind == _kind.SIGNAL:
return _SignalWaiter(gen)
# default
return _Waiter(gen)
示例3: _makeAST
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def _makeAST(f):
# Need to look at the flags used to compile the original function f and
# pass these same flags to the compile() function. This ensures that
# syntax-changing __future__ imports like print_function work correctly.
orig_f_co_flags = f.__code__.co_flags
# co_flags can contain various internal flags that we can't pass to
# compile(), so strip them out here
valid_flags = 0
for future_feature in __future__.all_feature_names:
feature = getattr(__future__, future_feature)
valid_flags |= feature.compiler_flag
s = inspect.getsource(f)
s = _dedent(s)
# use compile instead of ast.parse so that additional flags can be passed
flags = ast.PyCF_ONLY_AST | (orig_f_co_flags & valid_flags)
tree = compile(s, filename='<unknown>', mode='exec',
flags=flags, dont_inherit=True)
# tree = ast.parse(s)
tree.sourcefile = inspect.getsourcefile(f)
tree.lineoffset = inspect.getsourcelines(f)[1] - 1
return tree
示例4: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def __init__(self, *parts, **kwargs):
self.lines = lines = []
de = kwargs.get('deindent', True)
rstrip = kwargs.get('rstrip', True)
for part in parts:
if not part:
partlines = []
if isinstance(part, Source):
partlines = part.lines
elif isinstance(part, (tuple, list)):
partlines = [x.rstrip("\n") for x in part]
elif isinstance(part, py.builtin._basestring):
partlines = part.split('\n')
if rstrip:
while partlines:
if partlines[-1].strip():
break
partlines.pop()
else:
partlines = getsource(part, deindent=de).lines
if de:
partlines = deindent(partlines)
lines.extend(partlines)
示例5: test_deindent
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def test_deindent():
from py._code.source import deindent as deindent
assert deindent(['\tfoo', '\tbar', ]) == ['foo', 'bar']
def f():
c = '''while True:
pass
'''
import inspect
lines = deindent(inspect.getsource(f).splitlines())
assert lines == ["def f():", " c = '''while True:", " pass", "'''"]
source = """
def f():
def g():
pass
"""
lines = deindent(source.splitlines())
assert lines == ['', 'def f():', ' def g():', ' pass', ' ']
示例6: test_tabs
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def test_tabs():
"""Test that there are no tabs in our source files."""
ignore = _tab_ignores[:]
for importer, modname, ispkg in walk_packages(celer.__path__,
prefix='celer.'):
if not ispkg and modname not in ignore:
# mod = importlib.import_module(modname) # not py26 compatible!
try:
with warnings.catch_warnings(record=True): # traits
__import__(modname)
except Exception: # can't import properly
continue
mod = sys.modules[modname]
try:
source = getsource(mod)
except IOError: # user probably should have run "make clean"
continue
assert '\t' not in source, ('"%s" has tabs, please remove them '
'or add it to the ignore list'
% modname)
示例7: parse_types
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def parse_types(func: Callable) -> List[Tuple[Dict[str, str], str]]:
source = inspect.getsource(func)
signature = inspect.signature(func)
# Parse `# type: (...) -> ...` annotation. Note that it is allowed to pass
# multiple `# type:` annotations in `forward()`.
iterator = re.finditer(r'#\s*type:\s*\((.*)\)\s*->\s*(.*)\s*\n', source)
matches = list(iterator)
if len(matches) > 0:
out = []
args = list(signature.parameters.keys())
for match in matches:
arg_types_repr, return_type = match.groups()
arg_types = split_types_repr(arg_types_repr)
arg_types = OrderedDict((k, v) for k, v in zip(args, arg_types))
return_type = return_type.split('#')[0].strip()
out.append((arg_types, return_type))
return out
# Alternatively, parse annotations using the inspected signature.
else:
ps = signature.parameters
arg_types = OrderedDict((k, param_type_repr(v)) for k, v in ps.items())
return [(arg_types, return_type_repr(signature))]
示例8: preprocess_method_body
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def preprocess_method_body(source_code_obj):
src = inspect.getsource(source_code_obj)
ast_tree = ast.parse(src)
visitor = RewriteDicts()
ast_tree = visitor.visit(ast_tree)
ast.fix_missing_locations(ast_tree)
updated_code = compile(ast_tree, filename='<ast>', mode='exec')
bc = Bytecode.from_code(updated_code)
dlist = visitor.updated_dicts
RewriteDicts.updated_dicts = []
RewriteDicts.last_store_name = None
block_code = get_code_block(bc)
return block_code.arg, dlist
示例9: testSymbolicDims
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def testSymbolicDims(self):
p = builder.Base.Params()
b = p.Instantiate()
f1 = tshape.Shape(['kh', 'kw', 'idims', 'odims'])
kh, kw, idims, odims = f1
f2 = tshape.Shape([kh, kw, odims, odims])
p = b._Seq('test', b._Conv2D('conv', f1, (2, 2)),
b._Conv2D('conv', f2, (2, 2)), b._Bias('bias', odims))
inp = tshape.Shape(['b', 'h', 'w', idims])
b, h, w, _ = inp
meta = p.cls.FPropMeta(p, inp)
print('flops = ', meta.flops)
out = meta.out_shapes[0]
print('outputs = ', out)
# sympy.lambdify can help us to do faster numerical evaluation.
# Might be useful to build a "cost" model given a builder layer.
f = sympy.lambdify([b, h, w, kh, kw, idims, odims], meta.flops, 'numpy')
print('f.source = ', inspect.getsource(f))
self.assertEqual(f(8, 224, 224, 3, 3, 8, 32), 925646848)
self.assertEqual(f(8, 224, 224, 5, 5, 8, 32), 2569814016)
示例10: _install_linecache_wrapper
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def _install_linecache_wrapper(self):
"""Disable linecache.checkcache to not invalidate caches.
This gets installed permanently to also bypass e.g. pytest using
`inspect.getsource`, which would invalidate it outside of the
interaction them.
"""
if not hasattr(self, "_orig_linecache_checkcache"):
import linecache
# Save it, although not used really (can be useful for debugging).
self._orig_linecache_checkcache = linecache.checkcache
def _linecache_checkcache(*args, **kwargs):
return
linecache.checkcache = _linecache_checkcache
示例11: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def __init__(self, *parts, **kwargs):
self.lines = lines = []
de = kwargs.get("deindent", True)
for part in parts:
if not part:
partlines = []
elif isinstance(part, Source):
partlines = part.lines
elif isinstance(part, (tuple, list)):
partlines = [x.rstrip("\n") for x in part]
elif isinstance(part, str):
partlines = part.split("\n")
else:
partlines = getsource(part, deindent=de).lines
if de:
partlines = deindent(partlines)
lines.extend(partlines)
示例12: test_proceed_with_fake_filename
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def test_proceed_with_fake_filename(self):
'''doctest monkeypatches linecache to enable inspection'''
fn, source = '<test>', 'def x(): pass\n'
getlines = linecache.getlines
def monkey(filename, module_globals=None):
if filename == fn:
return source.splitlines(True)
else:
return getlines(filename, module_globals)
linecache.getlines = monkey
try:
ns = {}
exec compile(source, fn, 'single') in ns
inspect.getsource(ns["x"])
finally:
linecache.getlines = getlines
示例13: __init__
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def __init__(self, func):
super().__init__()
self.inst = func
self.name = func.__name__
self.filename = inspect.getfile(func)
sourcelines = inspect.getsourcelines(func)
self.lineno = sourcelines[1]
self.args.analyze_args(func)
if (func.__name__ == (lambda: None).__name__):
original_code = utils.lambda_source(func)
code = 'return ' + original_code[re.search('lambda.*?:', original_code).end():]
self.ast = gast.ast_to_gast(ast.parse(code))
else:
original_code = inspect.getsource(func)
code = utils.clip_head(original_code)
ast_ = gast.ast_to_gast(ast.parse(code)).body[0]
self.ast = canonicalizer.Canonicalizer().visit(ast_)
示例14: _set_function
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def _set_function(self, value):
"""setter of function"""
try:
check_var("function", value, "list")
except CheckTypeError:
check_var("function", value, "function")
if isinstance(value, list): # Load function from saved dict
self._function = [loads(value[0].encode("ISO-8859-2")), value[1]]
elif value is None:
self._function = [None, None]
elif callable(value):
self._function = [value, getsource(value)]
else:
raise TypeError(
"Expected function or list from a saved file, got: " + str(type(value))
)
# Function of the space to initiate the variable
# Type : function
示例15: _set_selector
# 需要導入模塊: import inspect [as 別名]
# 或者: from inspect import getsource [as 別名]
def _set_selector(self, value):
"""setter of selector"""
try:
check_var("selector", value, "list")
except CheckTypeError:
check_var("selector", value, "function")
if isinstance(value, list): # Load function from saved dict
self._selector = [loads(value[0].encode("ISO-8859-2")), value[1]]
elif value is None:
self._selector = [None, None]
elif callable(value):
self._selector = [value, getsource(value)]
else:
raise TypeError(
"Expected function or list from a saved file, got: " + str(type(value))
)
# Selector of the genetic algorithm
# Type : function