Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
Github issue #319.
"""
s = dedent("""\
def static(func):
def wrapped(obj, *args):
return f(type(obj), *args)
return wrapped
class C(object):
@static
def test(cls):
return 10
C().test(""")
signatures = Script(s).call_signatures()
assert len(signatures) == 1
x = [p.description for p in signatures[0].params]
assert x == ['*args']
def test_end_pos_one_line(self):
parsed = parser.Parser(parser.load_grammar(), dedent(u('''
def testit():
a = "huhu"
''')))
tok = parsed.module.subscopes[0].statements[0].children[2]
assert tok.end_pos == (3, 14)
def get_call(self, source):
stmt = Parser(u(source), no_docstr=True).module.statements[0]
return stmt.expression_list()[0]
return ""
params = post_data[:idx].split(",")
if len(params) != 3:
print("jedi-server/complete: invalid post code=2")
return ""
line, column, filename = params
line, column = int(line), int(column)
source = post_data[idx + 2:]
print("jedi-server/complete: ", line, column, filename)
# do completion
def print_candidate(type_, typed_text, arguement):
# row format: type$typed_text$arguemnt
return "{0}${1}${2}\n".format(type_, typed_text, arguement)
script = jedi.Script(source, line, column)
completions = script.completions()
# output compltion results
result = ""
for c in completions:
if c.type in ["function", "class"]:
if hasattr(c, "params"): # c is callable
sig = "({0})".format(
", ".join(map(lambda x: x.description, c.params)))
result += print_candidate(c.type, c.name, sig)
else:
result += print_candidate(c.type, c.name, "")
elif c.type in ["statement", "instance", "module", "import", "param"]:
result += print_candidate(c.type, c.name, "")
elif c.type == "keyword":
pass # ignore keyword
else:
jediPath = sys.argv[2]
jediPreview = True
cachePrefix = "custom_v"
if len(sys.argv) > 3:
modulesToLoad = sys.argv[3]
else:
# release
jediPath = os.path.join(os.path.dirname(__file__), "lib", "python")
if len(sys.argv) > 1:
modulesToLoad = sys.argv[1]
sys.path.insert(0, jediPath)
import jedi
if jediPreview:
jedi.settings.cache_directory = os.path.join(
jedi.settings.cache_directory,
cachePrefix + jedi.__version__.replace(".", ""),
)
# remove jedi from path after we import it so it will not be completed
sys.path.pop(0)
if len(modulesToLoad) > 0:
jedi.preload_module(*modulesToLoad.split(","))
JediCompletion().watch()
@memoize_default(default=[], evaluator_is_first_arg=True)
@recursion.recursion_decorator
@debug.increase_indent
def eval_statement(self, stmt, seek_name=None):
"""
The starting point of the completion. A statement always owns a call
list, which are the calls, that a statement does. In case multiple
names are defined in the statement, `seek_name` returns the result for
this name.
:param stmt: A `tree.ExprStmt`.
"""
debug.dbg('eval_statement %s (%s)', stmt, seek_name)
types = self.eval_element(stmt.get_rhs())
if seek_name:
types = finder.check_tuple_assignments(types, seek_name)
first_operation = stmt.first_operation()
if first_operation not in ('=', None) and not isinstance(stmt, er.InstanceElement): # TODO don't check for this.
# `=` is always the last character in aug assignments -> -1
operator = copy.copy(first_operation)
operator.value = operator.value[:-1]
name = str(stmt.get_defined_names()[0])
parent = self.wrap(stmt.get_parent_scope())
left = self.find_types(parent, name, stmt.start_pos, search_global=True)
if isinstance(stmt.get_parent_until(tree.ForStmt), tree.ForStmt):
# Iterate through result and add the values, that's possible
# only in for loops without clutter, because they are
# If there are annotations, prefer them over anything else.
# This will make it faster.
return value_set
value_set |= docstrings.infer_return_types(self._value)
returns = funcdef.iter_return_stmts()
for r in returns:
if check_yields:
value_set |= ValueSet.from_sets(
lazy_value.infer()
for lazy_value in self._get_yield_lazy_value(r)
)
else:
check = flow_analysis.reachability_check(self, funcdef, r)
if check is flow_analysis.UNREACHABLE:
debug.dbg('Return unreachable: %s', r)
else:
try:
children = r.children
except AttributeError:
ctx = compiled.builtin_from_name(self.inference_state, u'None')
value_set |= ValueSet([ctx])
else:
value_set |= self.infer_node(children[1])
if check is flow_analysis.REACHABLE:
debug.dbg('Return reachable: %s', r)
break
return value_set
def detect_django_path(module_path):
""" Detects the path of the very well known Django library (if used) """
result = []
while True:
new = os.path.dirname(module_path)
# If the module_path doesn't change anymore, we're finished -> /
if new == module_path:
break
else:
module_path = new
with common.ignored(IOError):
with open(module_path + os.path.sep + 'manage.py'):
debug.dbg('Found django path: %s' % module_path)
result.append(module_path)
return result
def search_in_module(inference_state, module_context, names, wanted_names,
wanted_type, complete=False, fuzzy=False,
ignore_imports=False, convert=False):
for s in wanted_names[:-1]:
new_names = []
for n in names:
if s == n.string_name:
if n.tree_name is not None and n.api_type == 'module' \
and ignore_imports:
continue
new_names += complete_trailer(
module_context,
n.infer()
)
debug.dbg('dot lookup on search %s from %s', new_names, names[:10])
names = new_names
last_name = wanted_names[-1].lower()
for n in names:
string = n.string_name.lower()
if complete and helpers.match(string, last_name, fuzzy=fuzzy) \
or not complete and string == last_name:
if isinstance(n, SubModuleName):
names = [v.name for v in n.infer()]
else:
names = [n]
if convert:
names = convert_names(names)
for n2 in names:
if complete:
def_ = classes.Completion(
def _decorated_func(self):
"""
Returns the function, that is to be executed in the end.
This is also the places where the decorators are processed.
"""
f = self.base_func
# Only enter it, if has not already been processed.
if not self.is_decorated:
for dec in reversed(self.base_func.decorators):
debug.dbg('decorator: %s %s', dec, f)
dec_results = self._evaluator.eval_statement(dec)
if not len(dec_results):
debug.warning('decorator not found: %s on %s', dec, self.base_func)
return None
decorator = dec_results.pop()
if dec_results:
debug.warning('multiple decorators found %s %s',
self.base_func, dec_results)
# Create param array.
old_func = Function(self._evaluator, f, is_decorated=True)
wrappers = self._evaluator.execute(decorator, (old_func,))
if not len(wrappers):
debug.warning('no wrappers found %s', self.base_func)
return None
if len(wrappers) > 1: