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