Commit afe3abb6 authored by Stefan Behnel's avatar Stefan Behnel

Modernise code: use set literals/comprehensions where possible, frozenset where appropriate.

parent 6ba500e3
......@@ -613,10 +613,10 @@ class DependencyTree(object):
@cached_method
def immediate_dependencies(self, filename):
all = set([filename])
all.update(self.cimported_files(filename))
all.update(self.included_files(filename))
return all
all_deps = {filename}
all_deps.update(self.cimported_files(filename))
all_deps.update(self.included_files(filename))
return all_deps
def all_dependencies(self, filename):
return self.transitive_merge(filename, self.immediate_dependencies, set.union)
......@@ -759,7 +759,7 @@ def create_extension_list(patterns, exclude=None, ctx=None, aliases=None, quiet=
return [], {}
elif isinstance(patterns, basestring) or not isinstance(patterns, Iterable):
patterns = [patterns]
explicit_modules = set([m.name for m in patterns if isinstance(m, Extension)])
explicit_modules = {m.name for m in patterns if isinstance(m, Extension)}
seen = set()
deps = create_dependency_tree(ctx, quiet=quiet)
to_exclude = set()
......
......@@ -346,15 +346,15 @@ builtin_types_table = [
]
types_that_construct_their_instance = set([
types_that_construct_their_instance = frozenset({
# some builtin types do not always return an instance of
# themselves - these do:
'type', 'bool', 'long', 'float', 'complex',
'bytes', 'unicode', 'bytearray',
'tuple', 'list', 'dict', 'set', 'frozenset'
'tuple', 'list', 'dict', 'set', 'frozenset',
# 'str', # only in Py3.x
# 'file', # only in Py2.x
])
})
builtin_structs_table = [
......
......@@ -100,12 +100,12 @@ uncachable_builtins = [
'_', # e.g. used by gettext
]
special_py_methods = frozenset((
special_py_methods = cython.declare(frozenset, frozenset((
'__cinit__', '__dealloc__', '__richcmp__', '__next__',
'__await__', '__aiter__', '__anext__',
'__getreadbuffer__', '__getwritebuffer__', '__getsegcount__',
'__getcharbuffer__', '__getbuffer__', '__releasebuffer__'
))
'__getcharbuffer__', '__getbuffer__', '__releasebuffer__',
)))
modifier_output_mapper = {
'inline': 'CYTHON_INLINE'
......
......@@ -183,7 +183,7 @@ def infer_sequence_item_type(env, seq_node, index_node=None, seq_type=None):
else:
return item.infer_type(env)
# if we're lucky, all items have the same type
item_types = set([item.infer_type(env) for item in seq_node.args])
item_types = {item.infer_type(env) for item in seq_node.args}
if len(item_types) == 1:
return item_types.pop()
return None
......@@ -6535,8 +6535,10 @@ class GeneralCallNode(CallNode):
len(pos_args)))
return None
matched_args = set([ arg.name for arg in declared_args[:len(pos_args)]
if arg.name ])
matched_args = {
arg.name for arg in declared_args[:len(pos_args)]
if arg.name
}
unmatched_args = declared_args[len(pos_args):]
matched_kwargs_count = 0
args = list(pos_args)
......@@ -8760,7 +8762,7 @@ class SetNode(ExprNode):
return False
def calculate_constant_result(self):
self.constant_result = set([arg.constant_result for arg in self.args])
self.constant_result = {arg.constant_result for arg in self.args}
def compile_time_value(self, denv):
values = [arg.compile_time_value(denv) for arg in self.args]
......@@ -11810,10 +11812,10 @@ _find_formatting_types = re.compile(
br")").findall
# These format conversion types can never trigger a Unicode string conversion in Py2.
_safe_bytes_formats = set([
_safe_bytes_formats = frozenset({
# Excludes 's' and 'r', which can generate non-bytes strings.
b'd', b'i', b'o', b'u', b'x', b'X', b'e', b'E', b'f', b'F', b'g', b'G', b'c', b'b', b'a',
])
})
class ModNode(DivNode):
......
......@@ -52,7 +52,7 @@ class ControlBlock(object):
stats = [Assignment(a), NameReference(a), NameReference(c),
Assignment(b)]
gen = {Entry(a): Assignment(a), Entry(b): Assignment(b)}
bounded = set([Entry(a), Entry(c)])
bounded = {Entry(a), Entry(c)}
"""
......@@ -203,7 +203,7 @@ class ControlFlow(object):
def normalize(self):
"""Delete unreachable and orphan blocks."""
queue = set([self.entry_point])
queue = {self.entry_point}
visited = set()
while queue:
root = queue.pop()
......
......@@ -115,9 +115,11 @@ class VerboseCodeWriter(type):
class CheckAnalysers(type):
"""Metaclass to check that type analysis functions return a node.
"""
methods = set(['analyse_types',
'analyse_expressions',
'analyse_target_types'])
methods = frozenset({
'analyse_types',
'analyse_expressions',
'analyse_target_types',
})
def __new__(cls, name, bases, attrs):
from types import FunctionType
......
......@@ -1236,7 +1236,7 @@ class SwitchTransform(Visitor.EnvTransform):
# integers on iteration, whereas Py2 returns 1-char byte
# strings
characters = string_literal.value
characters = list(set([ characters[i:i+1] for i in range(len(characters)) ]))
characters = list({ characters[i:i+1] for i in range(len(characters)) })
characters.sort()
return [ ExprNodes.CharNode(string_literal.pos, value=charval,
constant_result=charval)
......@@ -1248,7 +1248,8 @@ class SwitchTransform(Visitor.EnvTransform):
return self.NO_MATCH
elif common_var is not None and not is_common_value(var, common_var):
return self.NO_MATCH
elif not (var.type.is_int or var.type.is_enum) or sum([not (cond.type.is_int or cond.type.is_enum) for cond in conditions]):
elif not (var.type.is_int or var.type.is_enum) or any(
[not (cond.type.is_int or cond.type.is_enum) for cond in conditions]):
return self.NO_MATCH
return not_in, var, conditions
......@@ -2750,7 +2751,7 @@ class OptimizeBuiltinCalls(Visitor.NodeRefCleanupMixin,
Builtin.dict_type: "PyDict_Size",
}.get
_ext_types_with_pysize = set(["cpython.array.array"])
_ext_types_with_pysize = {"cpython.array.array"}
def _handle_simple_function_len(self, node, function, pos_args):
"""Replace len(char*) by the equivalent call to strlen(),
......
......@@ -685,17 +685,19 @@ class InterpretCompilerDirectives(CythonTransform):
'operator.comma' : ExprNodes.c_binop_constructor(','),
}
special_methods = set(['declare', 'union', 'struct', 'typedef',
'sizeof', 'cast', 'pointer', 'compiled',
'NULL', 'fused_type', 'parallel'])
special_methods = {
'declare', 'union', 'struct', 'typedef',
'sizeof', 'cast', 'pointer', 'compiled',
'NULL', 'fused_type', 'parallel',
}
special_methods.update(unop_method_nodes)
valid_parallel_directives = set([
valid_parallel_directives = {
"parallel",
"prange",
"threadid",
#"threadsavailable",
])
}
def __init__(self, context, compilation_directive_defaults):
super(InterpretCompilerDirectives, self).__init__(context)
......
......@@ -257,10 +257,10 @@ def p_cmp_op(s):
op = '!='
return op
comparison_ops = cython.declare(set, set([
comparison_ops = cython.declare(frozenset, frozenset((
'<', '>', '==', '>=', '<=', '<>', '!=',
'in', 'is', 'not'
]))
)))
#expr: xor_expr ('|' xor_expr)*
......@@ -829,7 +829,7 @@ def p_cat_string_literal(s):
continue
elif next_kind != kind:
# concatenating f strings and normal strings is allowed and leads to an f string
if set([kind, next_kind]) in (set(['f', 'u']), set(['f', ''])):
if {kind, next_kind} in ({'f', 'u'}, {'f', ''}):
kind = 'f'
else:
error(pos, "Cannot mix string literals of different types, expected %s'', got %s''" % (
......@@ -1486,8 +1486,8 @@ def p_genexp(s, expr):
expr.pos, expr = ExprNodes.YieldExprNode(expr.pos, arg=expr)))
return ExprNodes.GeneratorExpressionNode(expr.pos, loop=loop)
expr_terminators = cython.declare(set, set([
')', ']', '}', ':', '=', 'NEWLINE']))
expr_terminators = cython.declare(frozenset, frozenset((
')', ']', '}', ':', '=', 'NEWLINE')))
#-------------------------------------------------------
......@@ -1792,7 +1792,8 @@ def p_from_import_statement(s, first_statement = 0):
items = items)
imported_name_kinds = cython.declare(set, set(['class', 'struct', 'union']))
imported_name_kinds = cython.declare(frozenset, frozenset((
'class', 'struct', 'union')))
def p_imported_name(s, is_cimport):
pos = s.position()
......@@ -1839,7 +1840,8 @@ def p_assert_statement(s):
return Nodes.AssertStatNode(pos, condition=cond, value=value)
statement_terminators = cython.declare(set, set([';', 'NEWLINE', 'EOF']))
statement_terminators = cython.declare(frozenset, frozenset((
';', 'NEWLINE', 'EOF')))
def p_if_statement(s):
# s.sy == 'if'
......@@ -1949,7 +1951,8 @@ def p_for_from_step(s):
else:
return None
inequality_relations = cython.declare(set, set(['<', '<=', '>', '>=']))
inequality_relations = cython.declare(frozenset, frozenset((
'<', '<=', '>', '>=')))
def p_target(s, terminator):
pos = s.position()
......@@ -2463,8 +2466,8 @@ def p_calling_convention(s):
return ""
calling_convention_words = cython.declare(
set, set(["__stdcall", "__cdecl", "__fastcall"]))
calling_convention_words = cython.declare(frozenset, frozenset((
"__stdcall", "__cdecl", "__fastcall")))
def p_c_complex_base_type(s, templates = None):
......@@ -2743,8 +2746,8 @@ def looking_at_call(s):
s.start_line, s.start_col = position
return result
basic_c_type_names = cython.declare(
set, set(["void", "char", "int", "float", "double", "bint"]))
basic_c_type_names = cython.declare(frozenset, frozenset((
"void", "char", "int", "float", "double", "bint")))
special_basic_c_types = cython.declare(dict, {
# name : (signed, longness)
......@@ -2758,8 +2761,8 @@ special_basic_c_types = cython.declare(dict, {
"Py_tss_t" : (1, 0),
})
sign_and_longness_words = cython.declare(
set, set(["short", "long", "signed", "unsigned"]))
sign_and_longness_words = cython.declare(frozenset, frozenset((
"short", "long", "signed", "unsigned")))
base_type_start_words = cython.declare(
set,
......@@ -2767,8 +2770,8 @@ base_type_start_words = cython.declare(
| sign_and_longness_words
| set(special_basic_c_types))
struct_enum_union = cython.declare(
set, set(["struct", "union", "enum", "packed"]))
struct_enum_union = cython.declare(frozenset, frozenset((
"struct", "union", "enum", "packed")))
def p_sign_and_longness(s):
signed = 1
......@@ -2853,13 +2856,13 @@ def p_c_func_declarator(s, pos, ctx, base, cmethod_flag):
exception_value = exc_val, exception_check = exc_check,
nogil = nogil or ctx.nogil or with_gil, with_gil = with_gil)
supported_overloaded_operators = cython.declare(set, set([
supported_overloaded_operators = cython.declare(frozenset, frozenset((
'+', '-', '*', '/', '%',
'++', '--', '~', '|', '&', '^', '<<', '>>', ',',
'==', '!=', '>=', '>', '<=', '<',
'[]', '()', '!', '=',
'bool',
]))
)))
def p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
assignable, nonempty):
......@@ -2981,7 +2984,8 @@ def p_exception_value_clause(s):
exc_val = p_test(s)
return exc_val, exc_check
c_arg_list_terminators = cython.declare(set, set(['*', '**', '.', ')', ':', '/']))
c_arg_list_terminators = cython.declare(frozenset, frozenset((
'*', '**', '.', ')', ':', '/')))
def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
nonempty_declarators = 0, kw_only = 0, annotated = 1):
......
......@@ -1339,14 +1339,14 @@ class PyObjectType(PyrexType):
return cname
builtin_types_that_cannot_create_refcycles = set([
builtin_types_that_cannot_create_refcycles = frozenset({
'object', 'bool', 'int', 'long', 'float', 'complex',
'bytearray', 'bytes', 'unicode', 'str', 'basestring'
])
'bytearray', 'bytes', 'unicode', 'str', 'basestring',
})
builtin_types_with_trashcan = set([
builtin_types_with_trashcan = frozenset({
'dict', 'list', 'set', 'frozenset', 'tuple', 'type',
])
})
class BuiltinObjectType(PyObjectType):
......
......@@ -134,7 +134,7 @@ class TestDebugInformationClasses(DebugTestCase):
self.assertEqual(self.spam_func.arguments, ['a'])
self.assertEqual(self.spam_func.step_into_functions,
set(['puts', 'some_c_function']))
{'puts', 'some_c_function'})
expected_lineno = test_libcython.source_to_lineno['def spam(a=0):']
self.assertEqual(self.spam_func.lineno, expected_lineno)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment