How to use the jedi.common function in jedi

To help you get started, we’ve selected a few jedi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github paulwinex / pw_MultiScriptEditor / multi_script_editor / jedi / refactoring.py View on Github external
dct = {}
    current_path = object()
    new_lines = old_lines = None
    for name in order:
        if name.in_builtin_module():
            continue
        if current_path != name.module_path:
            current_path = name.module_path

            process(current_path, old_lines, new_lines)
            if current_path is not None:
                # None means take the source that is a normal param.
                with open(current_path) as f:
                    source = f.read()

            new_lines = common.splitlines(common.source_to_unicode(source))
            old_lines = new_lines[:]

        nr, indent = name.line, name.column
        line = new_lines[nr - 1]
        new_lines[nr - 1] = line[:indent] + replace_str + \
            line[indent + len(name.name):]
    process(current_path, old_lines, new_lines)
    return dct
github paulwinex / pw_MultiScriptEditor / multi_script_editor / jedi / api / __init__.py View on Github external
encoding='utf-8', source_path=None, source_encoding=None):
        if source_path is not None:
            warnings.warn("Use path instead of source_path.", DeprecationWarning)
            path = source_path
        if source_encoding is not None:
            warnings.warn("Use encoding instead of source_encoding.", DeprecationWarning)
            encoding = source_encoding

        self._orig_path = path
        self.path = None if path is None else os.path.abspath(path)

        if source is None:
            with open(path) as f:
                source = f.read()

        self.source = common.source_to_unicode(source, encoding)
        lines = common.splitlines(self.source)
        line = max(len(lines), 1) if line is None else line
        if not (0 < line <= len(lines)):
            raise ValueError('`line` parameter is not in a valid range.')

        line_len = len(lines[line - 1])
        column = line_len if column is None else column
        if not (0 <= column <= line_len):
            raise ValueError('`column` parameter is not in a valid range.')
        self._pos = line, column

        cache.clear_caches()
        debug.reset_time()
        self._user_context = UserContext(self.source, self._pos)
        self._parser = UserContextParser(self.source, path, self._pos, self._user_context)
        self._evaluator = Evaluator()
github xleng / YCM_WIN_X86 / third_party / ycmd / third_party / jedi / jedi / parser / representation.py View on Github external
"""
        string = ""
        if self._doc_token is not None:
            string += '"""' + self.raw_doc + '"""\n'

        objs = self.subscopes + self.imports + self.statements + self.returns
        for obj in sorted(objs, key=lambda x: x.start_pos):
            if isinstance(obj, Scope):
                string += obj.get_code(first_indent=True, indention=indention)
            else:
                if obj in self.returns and not isinstance(self, Lambda):
                    string += 'yield ' if self.is_generator else 'return '
                string += obj.get_code()

        if first_indent:
            string = common.indent_block(string, indention=indention)
        return string
github facebookarchive / atom-ide-ui / modules / atom-ide-debugger-python / VendorLib / vs-py-debugger / pythonFiles / preview / jedi / evaluate / finder.py View on Github external
def _check_getattr(self, inst):
        """Checks for both __getattr__ and __getattribute__ methods"""
        result = set()
        # str is important, because it shouldn't be `Name`!
        name = compiled.create(self._evaluator, str(self.name_str))
        with common.ignored(KeyError):
            result = inst.execute_subscope_by_name('__getattr__', name)
        if not result:
            # This is a little bit special. `__getattribute__` is in Python
            # executed before `__getattr__`. But: I know no use case, where
            # this could be practical and where jedi would return wrong types.
            # If you ever find something, let me know!
            # We are inversing this, because a hand-crafted `__getattribute__`
            # could still call another hand-crafted `__getattr__`, but not the
            # other way around.
            with common.ignored(KeyError):
                result = inst.execute_subscope_by_name('__getattribute__', name)
        return result
github paulwinex / pw_MultiScriptEditor / multi_script_editor / jedi / evaluate / finder.py View on Github external
def _resolve_descriptors(self, types):
        """Processes descriptors"""
        result = []
        for r in types:
            if isinstance(self.scope, (er.Instance, er.Class)) \
                    and hasattr(r, 'get_descriptor_return'):
                # handle descriptors
                with common.ignored(KeyError):
                    result += r.get_descriptor_return(self.scope)
                    continue
            result.append(r)
        return result
github bazitur / brackets-python-tools / jedi / api / __init__.py View on Github external
path = source_path
        if source_encoding is not None:
            warnings.warn("Deprecated since version 0.8. Use encoding instead of source_encoding.", DeprecationWarning, stacklevel=2)
            encoding = source_encoding

        self._orig_path = path
        # An empty path (also empty string) should always result in no path.
        self.path = os.path.abspath(path) if path else None

        if source is None:
            # TODO add a better warning than the traceback!
            with open(path, 'rb') as f:
                source = f.read()

        self._source = common.source_to_unicode(source, encoding)
        self._code_lines = common.splitlines(self._source)
        line = max(len(self._code_lines), 1) if line is None else line
        if not (0 < line <= len(self._code_lines)):
            raise ValueError('`line` parameter is not in a valid range.')

        line_len = len(self._code_lines[line - 1])
        column = line_len if column is None else column
        if not (0 <= column <= line_len):
            raise ValueError('`column` parameter is not in a valid range.')
        self._pos = line, column
        self._path = path

        cache.clear_time_caches()
        debug.reset_time()
        self._grammar = load_grammar(version='%s.%s' % sys.version_info[:2])
        if sys_path is None:
            venv = os.getenv('VIRTUAL_ENV')
github srusskih / SublimeJEDI / jedi / evaluate / finder.py View on Github external
def _check_getattr(self, inst):
        """Checks for both __getattr__ and __getattribute__ methods"""
        result = []
        # str is important, because it shouldn't be `Name`!
        name = compiled.create(self._evaluator, str(self.name_str))
        with common.ignored(KeyError):
            result = inst.execute_subscope_by_name('__getattr__', name)
        if not result:
            # this is a little bit special. `__getattribute__` is executed
            # before anything else. But: I know no use case, where this
            # could be practical and the jedi would return wrong types. If
            # you ever have something, let me know!
            with common.ignored(KeyError):
                result = inst.execute_subscope_by_name('__getattribute__', name)
        return result
github srusskih / SublimeJEDI / jedi / evaluate / param.py View on Github external
def get_params(evaluator, func, var_args):
    param_names = []
    param_dict = {}
    for param in func.params:
        param_dict[str(param.name)] = param
    unpacked_va = list(var_args.unpack(func))
    from jedi.evaluate.representation import InstanceElement
    if isinstance(func, InstanceElement):
        # Include self at this place.
        unpacked_va.insert(0, (None, [iterable.AlreadyEvaluated([func.instance])]))
    var_arg_iterator = common.PushBackIterator(iter(unpacked_va))

    non_matching_keys = defaultdict(lambda: [])
    keys_used = {}
    keys_only = False
    had_multiple_value_error = False
    for param in func.params:
        # The value and key can both be null. There, the defaults apply.
        # args / kwargs will just be empty arrays / dicts, respectively.
        # Wrong value count is just ignored. If you try to test cases that are
        # not allowed in Python, Jedi will maybe not show any completions.
        default = [] if param.default is None else [param.default]
        key, va_values = next(var_arg_iterator, (None, default))
        while key is not None:
            keys_only = True
            k = unicode(key)
            try:
github srusskih / SublimeJEDI / jedi / evaluate / representation.py View on Github external
def return_value(search_path):
            init_path = self.py__file__()
            if os.path.basename(init_path) == '__init__.py':

                with open(init_path, 'rb') as f:
                    content = common.source_to_unicode(f.read())
                    # these are strings that need to be used for namespace packages,
                    # the first one is ``pkgutil``, the second ``pkg_resources``.
                    options = ('declare_namespace(__name__)', 'extend_path(__path__')
                    if options[0] in content or options[1] in content:
                        # It is a namespace, now try to find the rest of the
                        # modules on sys_path or whatever the search_path is.
                        paths = set()
                        for s in search_path:
                            other = os.path.join(s, unicode(self.name))
                            if os.path.isdir(other):
                                paths.add(other)
                        return list(paths)
            # Default to this.
            return [path]
github paulwinex / pw_MultiScriptEditor / multi_script_editor / jedi / parser / user_context.py View on Github external
def get_line(self, line_nr):
        if not self._line_cache:
            self._line_cache = common.splitlines(self.source)

        if line_nr == 0:
            # This is a fix for the zeroth line. We need a newline there, for
            # the backwards parser.
            return u('')
        if line_nr < 0:
            raise StopIteration()
        try:
            return self._line_cache[line_nr - 1]
        except IndexError:
            raise StopIteration()