Remove __str__ from name.

This commit is contained in:
Dave Halter
2017-04-12 23:06:11 +02:00
parent 73a38267cf
commit d6d25db9a2
11 changed files with 42 additions and 39 deletions

View File

@@ -160,7 +160,7 @@ class Evaluator(object):
# `=` is always the last character in aug assignments -> -1 # `=` is always the last character in aug assignments -> -1
operator = copy.copy(first_operator) operator = copy.copy(first_operator)
operator.value = operator.value[:-1] operator.value = operator.value[:-1]
name = str(stmt.get_defined_names()[0]) name = stmt.get_defined_names()[0].value
left = context.py__getattribute__( left = context.py__getattribute__(
name, position=stmt.start_pos, search_global=True) name, position=stmt.start_pos, search_global=True)
@@ -175,7 +175,7 @@ class Evaluator(object):
ordered = list(iterable.py__iter__(self, cn.infer(), cn)) ordered = list(iterable.py__iter__(self, cn.infer(), cn))
for lazy_context in ordered: for lazy_context in ordered:
dct = {str(for_stmt.children[1]): lazy_context.infer()} dct = {for_stmt.children[1].value: lazy_context.infer()}
with helpers.predefine_names(context, for_stmt, dct): with helpers.predefine_names(context, for_stmt, dct):
t = self.eval_element(context, rhs) t = self.eval_element(context, rhs)
left = precedence.calculate(self, context, left, operator, t) left = precedence.calculate(self, context, left, operator, t)
@@ -210,8 +210,8 @@ class Evaluator(object):
# names in the suite. # names in the suite.
if_names = helpers.get_names_of_node(if_stmt_test) if_names = helpers.get_names_of_node(if_stmt_test)
element_names = helpers.get_names_of_node(element) element_names = helpers.get_names_of_node(element)
str_element_names = [str(e) for e in element_names] str_element_names = [e.value for e in element_names]
if any(str(i) in str_element_names for i in if_names): if any(i.value in str_element_names for i in if_names):
for if_name in if_names: for if_name in if_names:
definitions = self.goto_definitions(context, if_name) definitions = self.goto_definitions(context, if_name)
# Every name that has multiple different definitions # Every name that has multiple different definitions
@@ -232,12 +232,12 @@ class Evaluator(object):
new_name_dicts = list(original_name_dicts) new_name_dicts = list(original_name_dicts)
for i, name_dict in enumerate(new_name_dicts): for i, name_dict in enumerate(new_name_dicts):
new_name_dicts[i] = name_dict.copy() new_name_dicts[i] = name_dict.copy()
new_name_dicts[i][str(if_name)] = set([definition]) new_name_dicts[i][if_name.value] = set([definition])
name_dicts += new_name_dicts name_dicts += new_name_dicts
else: else:
for name_dict in name_dicts: for name_dict in name_dicts:
name_dict[str(if_name)] = definitions name_dict[if_name.value] = definitions
if len(name_dicts) > 1: if len(name_dicts) > 1:
result = set() result = set()
for name_dict in name_dicts: for name_dict in name_dicts:

View File

@@ -190,7 +190,7 @@ def _check_for_exception_catch(node_context, jedi_name, exception, payload=None)
key, lazy_context = args[1] key, lazy_context = args[1]
names = list(lazy_context.infer()) names = list(lazy_context.infer())
assert len(names) == 1 and isinstance(names[0], CompiledObject) assert len(names) == 1 and isinstance(names[0], CompiledObject)
assert names[0].obj == str(payload[1]) assert names[0].obj == payload[1].value
# Check objects # Check objects
key, lazy_context = args[0] key, lazy_context = args[0]

View File

@@ -188,8 +188,9 @@ def _execute_array_values(evaluator, array):
def follow_param(module_context, param): def follow_param(module_context, param):
def eval_docstring(docstring): def eval_docstring(docstring):
return set( return set(
[p for param_str in _search_param_in_docstr(docstring, str(param.name)) p
for p in _evaluate_for_statement_string(module_context, param_str)] for param_str in _search_param_in_docstr(docstring, param.name.value)
for p in _evaluate_for_statement_string(module_context, param_str)
) )
func = param.get_parent_function() func = param.get_parent_function()
if func.type == 'lambdef': if func.type == 'lambdef':

View File

@@ -118,7 +118,7 @@ class NameFinder(object):
break break
for filter in filters: for filter in filters:
names = filter.get(self._name) names = filter.get(self._string_name)
if names: if names:
break break
debug.dbg('finder.filter_name "%s" in (%s): %s@%s', self._string_name, debug.dbg('finder.filter_name "%s" in (%s): %s@%s', self._string_name,
@@ -199,7 +199,7 @@ def _name_to_types(evaluator, context, tree_name):
types = _apply_decorators(evaluator, context, node) types = _apply_decorators(evaluator, context, node)
elif typ == 'global_stmt': elif typ == 'global_stmt':
context = evaluator.create_context(context, tree_name) context = evaluator.create_context(context, tree_name)
finder = NameFinder(evaluator, context, context, str(tree_name)) finder = NameFinder(evaluator, context, context, tree_name.value)
filters = finder.get_filters(search_global=True) filters = finder.get_filters(search_global=True)
# For global_stmt lookups, we only need the first possible scope, # For global_stmt lookups, we only need the first possible scope,
# which means the function itself. # which means the function itself.

View File

@@ -63,7 +63,7 @@ def infer_import(context, tree_name, is_goto=False):
if from_import_name is not None: if from_import_name is not None:
types = unite( types = unite(
t.py__getattribute__( t.py__getattribute__(
unicode(from_import_name), from_import_name.value if isinstance(from_import_name, tree.Name) else from_import_name,
name_context=context, name_context=context,
is_goto=is_goto is_goto=is_goto
) for t in types ) for t in types
@@ -229,7 +229,9 @@ class Importer(object):
@property @property
def str_import_path(self): def str_import_path(self):
"""Returns the import path as pure strings instead of `Name`.""" """Returns the import path as pure strings instead of `Name`."""
return tuple(str(name) for name in self.import_path) return tuple(
name.value if isinstance(name, tree.Name) else name
for name in self.import_path)
def sys_path_with_modifications(self): def sys_path_with_modifications(self):
in_path = [] in_path = []
@@ -262,7 +264,10 @@ class Importer(object):
""" """
This method is very similar to importlib's `_gcd_import`. This method is very similar to importlib's `_gcd_import`.
""" """
import_parts = [str(i) for i in import_path] import_parts = [
i.value if isinstance(i, tree.Name) else i
for i in import_path
]
# Handle "magic" Flask extension imports: # Handle "magic" Flask extension imports:
# ``flask.ext.foo`` is really ``flask_foo`` or ``flaskext.foo``. # ``flask.ext.foo`` is really ``flask_foo`` or ``flaskext.foo``.
@@ -297,7 +302,7 @@ class Importer(object):
# ``os.path``, because it's a very important one in Python # ``os.path``, because it's a very important one in Python
# that is being achieved by messing with ``sys.modules`` in # that is being achieved by messing with ``sys.modules`` in
# ``os``. # ``os``.
if [str(i) for i in import_path] == ['os', 'path']: if import_parts == ['os', 'path']:
return parent_module.py__getattribute__('path') return parent_module.py__getattribute__('path')
try: try:

View File

@@ -236,7 +236,7 @@ def get_params(evaluator, parent_context, func, var_args):
result_params = [] result_params = []
param_dict = {} param_dict = {}
for param in func.params: for param in func.params:
param_dict[str(param.name)] = param param_dict[param.name.value] = param
unpacked_va = list(var_args.unpack(func)) unpacked_va = list(var_args.unpack(func))
var_arg_iterator = common.PushBackIterator(iter(unpacked_va)) var_arg_iterator = common.PushBackIterator(iter(unpacked_va))

View File

@@ -46,7 +46,7 @@ def calculate_children(evaluator, context, children):
for operator in iterator: for operator in iterator:
right = next(iterator) right = next(iterator)
if operator.type == 'comp_op': # not in / is not if operator.type == 'comp_op': # not in / is not
operator = ' '.join(str(c.value) for c in operator.children) operator = ' '.join(c.value for c in operator.children)
# handle lazy evaluation of and/or here. # handle lazy evaluation of and/or here.
if operator in ('and', 'or'): if operator in ('and', 'or'):

View File

@@ -397,7 +397,7 @@ class FunctionExecutionContext(context.TreeContext):
ordered = iterable.py__iter__(evaluator, cn.infer(), cn) ordered = iterable.py__iter__(evaluator, cn.infer(), cn)
ordered = list(ordered) ordered = list(ordered)
for lazy_context in ordered: for lazy_context in ordered:
dct = {str(for_stmt.children[1]): lazy_context.infer()} dct = {str(for_stmt.children[1].value): lazy_context.infer()}
with helpers.predefine_names(self, for_stmt, dct): with helpers.predefine_names(self, for_stmt, dct):
for yield_in_same_for_stmt in yields: for yield_in_same_for_stmt in yields:
for result in self._eval_yield(yield_in_same_for_stmt): for result in self._eval_yield(yield_in_same_for_stmt):

View File

@@ -220,12 +220,6 @@ class Name(_LeafWithoutNewlines):
type = 'name' type = 'name'
__slots__ = () __slots__ = ()
def __str__(self):
return self.value
def __unicode__(self):
return self.value
def __repr__(self): def __repr__(self):
return "<%s: %s@%s,%s>" % (type(self).__name__, self.value, return "<%s: %s@%s,%s>" % (type(self).__name__, self.value,
self.line, self.indent) self.line, self.indent)
@@ -351,7 +345,7 @@ class Scope(PythonBaseNode, DocstringMixin):
def __repr__(self): def __repr__(self):
try: try:
name = self.name name = self.name.value
except AttributeError: except AttributeError:
name = '' name = ''
@@ -396,7 +390,7 @@ class Module(Scope):
for imp in self.imports: for imp in self.imports:
if imp.type == 'import_from' and imp.level == 0: if imp.type == 'import_from' and imp.level == 0:
for path in imp.paths(): for path in imp.paths():
if [str(name) for name in path] == ['__future__', 'absolute_import']: if [name.value for name in path] == ['__future__', 'absolute_import']:
return True return True
return False return False
@@ -477,9 +471,9 @@ class Class(ClassOrFunc):
""" """
docstr = self.raw_doc docstr = self.raw_doc
for sub in self.subscopes: for sub in self.subscopes:
if str(sub.name) == '__init__': if sub.name.value == '__init__':
return '%s\n\n%s' % ( return '%s\n\n%s' % (
sub.get_call_signature(func_name=self.name), docstr) sub.get_call_signature(call_string=self.name.value), docstr)
return docstr return docstr
@@ -579,7 +573,7 @@ class Function(ClassOrFunc):
except IndexError: except IndexError:
return None return None
def get_call_signature(self, width=72, func_name=None): def get_call_signature(self, width=72, call_string=None):
""" """
Generate call signature of this function. Generate call signature of this function.
@@ -591,8 +585,12 @@ class Function(ClassOrFunc):
:rtype: str :rtype: str
""" """
# Lambdas have no name. # Lambdas have no name.
func_name = func_name or getattr(self, 'name', '<lambda>') if call_string is None:
code = unicode(func_name) + self._get_paramlist_code() if self.type == 'lambdef':
call_string = '<lambda>'
else:
call_string = self.name.value
code = call_string + self._get_paramlist_code()
return '\n'.join(textwrap.wrap(code, width)) return '\n'.join(textwrap.wrap(code, width))
def _get_paramlist_code(self): def _get_paramlist_code(self):

View File

@@ -20,7 +20,7 @@ def test_user_statement_on_import():
p = parse(s) p = parse(s)
stmt = p.get_statement_for_position(pos) stmt = p.get_statement_for_position(pos)
assert isinstance(stmt, tree.Import) assert isinstance(stmt, tree.Import)
assert [str(n) for n in stmt.get_defined_names()] == ['time'] assert [n.value for n in stmt.get_defined_names()] == ['time']
class TestCallAndName(): class TestCallAndName():
@@ -31,7 +31,7 @@ class TestCallAndName():
def test_name_and_call_positions(self): def test_name_and_call_positions(self):
name = self.get_call('name\nsomething_else') name = self.get_call('name\nsomething_else')
assert str(name) == 'name' assert name.value == 'name'
assert name.start_pos == (1, 0) assert name.start_pos == (1, 0)
assert name.end_pos == (1, 4) assert name.end_pos == (1, 4)
@@ -67,12 +67,12 @@ class TestSubscopes():
name = self.get_sub('class Foo: pass').name name = self.get_sub('class Foo: pass').name
assert name.start_pos == (1, len('class ')) assert name.start_pos == (1, len('class '))
assert name.end_pos == (1, len('class Foo')) assert name.end_pos == (1, len('class Foo'))
assert str(name) == 'Foo' assert name.value == 'Foo'
name = self.get_sub('def foo(): pass').name name = self.get_sub('def foo(): pass').name
assert name.start_pos == (1, len('def ')) assert name.start_pos == (1, len('def '))
assert name.end_pos == (1, len('def foo')) assert name.end_pos == (1, len('def foo'))
assert str(name) == 'foo' assert name.value == 'foo'
class TestImports(): class TestImports():
@@ -83,7 +83,7 @@ class TestImports():
imp = self.get_import(u('import math\n')) imp = self.get_import(u('import math\n'))
names = imp.get_defined_names() names = imp.get_defined_names()
assert len(names) == 1 assert len(names) == 1
assert str(names[0]) == 'math' assert names[0].value == 'math'
assert names[0].start_pos == (1, len('import ')) assert names[0].start_pos == (1, len('import '))
assert names[0].end_pos == (1, len('import math')) assert names[0].end_pos == (1, len('import math'))

View File

@@ -4,7 +4,6 @@ from textwrap import dedent
import pytest import pytest
from jedi._compatibility import u, unicode
from jedi.parser.python import parse from jedi.parser.python import parse
from jedi.parser.python import tree from jedi.parser.python import tree
@@ -38,12 +37,12 @@ class TestsFunctionAndLambdaParsing(object):
def test_name(self, node, expected): def test_name(self, node, expected):
if node.type != 'lambdef': if node.type != 'lambdef':
assert isinstance(node.name, tree.Name) assert isinstance(node.name, tree.Name)
assert unicode(node.name) == u(expected['name']) assert node.name.value == expected['name']
def test_params(self, node, expected): def test_params(self, node, expected):
assert isinstance(node.params, list) assert isinstance(node.params, list)
assert all(isinstance(x, tree.Param) for x in node.params) assert all(isinstance(x, tree.Param) for x in node.params)
assert [unicode(x.name) for x in node.params] == [u(x) for x in expected['params']] assert [str(x.name.value) for x in node.params] == [x for x in expected['params']]
def test_is_generator(self, node, expected): def test_is_generator(self, node, expected):
assert node.is_generator() is expected.get('is_generator', False) assert node.is_generator() is expected.get('is_generator', False)