Skip to content

Commit ae6f7a9

Browse files
author
Sourcery AI
committed
'Refactored by Sourcery'
1 parent 3221ad6 commit ae6f7a9

8 files changed

Lines changed: 155 additions & 215 deletions

File tree

pccm/core/__init__.py

Lines changed: 75 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -313,9 +313,7 @@ def __init__(self,
313313
self.scoped = scoped
314314

315315
def to_string(self) -> str:
316-
scoped_str = ""
317-
if self.scoped:
318-
scoped_str = "class"
316+
scoped_str = "class" if self.scoped else ""
319317
prefix = "enum {} {} {{".format(scoped_str, self.name)
320318
if self.base_type:
321319
prefix = "enum {} {}: {} {{".format(scoped_str, self.name,
@@ -362,13 +360,12 @@ def to_string(self) -> str:
362360
else:
363361
return "{}{} {} = {};".format(doc, self.type_str, self.name,
364362
self.default)
363+
elif self.default is None:
364+
return "{}{} {}{};".format(doc, self.type_str, self.name,
365+
self.array)
365366
else:
366-
if self.default is None:
367-
return "{}{} {}{};".format(doc, self.type_str, self.name,
368-
self.array)
369-
else:
370-
return "{}{} {}{} = {};".format(doc, self.type_str, self.name,
371-
self.array, self.default)
367+
return "{}{} {}{} = {};".format(doc, self.type_str, self.name,
368+
self.array, self.default)
372369

373370

374371
class TemplateTypeArgument(object):
@@ -535,18 +532,10 @@ def unpack(self, args: list) -> str:
535532
return ", ".join(map(str, args))
536533

537534
def _clean_pre_attrs_impl(self, attrs: List[str]):
538-
res_attrs = [] # type: List[str]
539-
for attr in attrs:
540-
if attr not in _HEADER_ONLY_PRE_ATTRS:
541-
res_attrs.append(attr)
542-
return res_attrs
535+
return [attr for attr in attrs if attr not in _HEADER_ONLY_PRE_ATTRS]
543536

544537
def _clean_post_attrs_impl(self, attrs: List[str]):
545-
res_attrs = [] # type: List[str]
546-
for attr in attrs:
547-
if attr not in _HEADER_ONLY_POST_ATTRS:
548-
res_attrs.append(attr)
549-
return res_attrs
538+
return [attr for attr in attrs if attr not in _HEADER_ONLY_POST_ATTRS]
550539

551540
def get_sig(self,
552541
name: str,
@@ -565,9 +554,8 @@ def get_sig(self,
565554
return_type = self.return_type
566555
if isinstance(meta, (ConstructorMeta, DestructorMeta)):
567556
return_type = ""
568-
else:
569-
if not header_only:
570-
assert self.return_type != "auto" and self.return_type != "decltype(auto)"
557+
elif not header_only:
558+
assert self.return_type not in ["auto", "decltype(auto)"]
571559
fmt = "{ret_type} {name}({args})"
572560
if withpost:
573561
fmt += "{post_attrs}"
@@ -650,8 +638,7 @@ def get_impl(self, name: str, meta: FunctionMeta, class_name: str = ""):
650638
post_attrs=post_attrs_str)
651639
if pre_attrs_str:
652640
prefix_fmt = pre_attrs_str + " " + prefix_fmt
653-
blocks = [] # List[Union[Block, str]]
654-
blocks.extend(self._blocks)
641+
blocks = list(self._blocks)
655642
block = Block(template_fmt + prefix_fmt, blocks, "}")
656643
if meta.macro_guard is not None:
657644
block = Block("#if {}".format(meta.macro_guard), [block], "#endif")
@@ -972,15 +959,18 @@ def _assign_overload_flag_to_func_decls(self):
972959
member_decl_count[cpp_func_name] += 1
973960
for decl in self._function_decls:
974961
cpp_func_name = decl.get_function_name()
975-
if isinstance(decl.meta, ExternalFunctionMeta):
976-
if extend_decl_count[cpp_func_name] > 1:
977-
decl.is_overload = True
978-
elif isinstance(decl.meta, StaticMemberFunctionMeta):
979-
if static_member_decl_count[cpp_func_name] > 1:
980-
decl.is_overload = True
981-
elif isinstance(decl.meta, MemberFunctionMeta):
982-
if member_decl_count[cpp_func_name] > 1:
983-
decl.is_overload = True
962+
if (
963+
isinstance(decl.meta, ExternalFunctionMeta)
964+
and extend_decl_count[cpp_func_name] > 1
965+
or not isinstance(decl.meta, ExternalFunctionMeta)
966+
and isinstance(decl.meta, StaticMemberFunctionMeta)
967+
and static_member_decl_count[cpp_func_name] > 1
968+
or not isinstance(decl.meta, ExternalFunctionMeta)
969+
and not isinstance(decl.meta, StaticMemberFunctionMeta)
970+
and isinstance(decl.meta, MemberFunctionMeta)
971+
and member_decl_count[cpp_func_name] > 1
972+
):
973+
decl.is_overload = True
984974

985975
def add_dependency(self, *no_param_class_cls: Type["Class"]):
986976
# TODO enable name alias for Class
@@ -1134,7 +1124,7 @@ def get_includes_with_dep(self) -> List[str]:
11341124
for d in self.get_common_deps())
11351125
return res
11361126

1137-
def get_parent_class(self): # -> Optional[Type["Class"]]
1127+
def get_parent_class(self): # -> Optional[Type["Class"]]
11381128
"""TODO find a better way to check invalid param class inherit
11391129
"""
11401130
if type(self) is Class:
@@ -1145,24 +1135,23 @@ def get_parent_class(self): # -> Optional[Type["Class"]]
11451135
base = candidates.pop()
11461136
if issubclass(base, Class):
11471137
cls_meta = get_class_meta(base)
1148-
if cls_meta is None:
1149-
pccm_base_types.append(base)
1138+
if cls_meta is not None and cls_meta.skip_inherit:
1139+
candidates.extend(base.__bases__)
11501140
else:
1151-
if cls_meta.skip_inherit:
1152-
candidates.extend(base.__bases__)
1153-
else:
1154-
pccm_base_types.append(base)
1141+
pccm_base_types.append(base)
11551142
assert len(pccm_base_types) == 1, "you can only inherit one class."
11561143
pccm_base = pccm_base_types[0]
1157-
if pccm_base is not Class and base is not ParameterizedClass:
1158-
# assert not issubclass(mro[1], ParameterizedClass), "you can't inherit a param class."
1159-
if not issubclass(pccm_base, ParameterizedClass):
1160-
# you inherit a class. you must set _this_cls_type by self.set_this_class_type(__class__)
1161-
msg = (
1162-
"you must use self.set_this_class_type(__class__) to init this class type"
1163-
" when you inherit pccm.Class")
1164-
assert self._this_cls_type is not None, msg
1165-
return pccm_base
1144+
if (
1145+
pccm_base is not Class
1146+
and base is not ParameterizedClass
1147+
and not issubclass(pccm_base, ParameterizedClass)
1148+
):
1149+
# you inherit a class. you must set _this_cls_type by self.set_this_class_type(__class__)
1150+
msg = (
1151+
"you must use self.set_this_class_type(__class__) to init this class type"
1152+
" when you inherit pccm.Class")
1153+
assert self._this_cls_type is not None, msg
1154+
return pccm_base
11661155
return None
11671156

11681157
def get_class_deps(self) -> List[Type["Class"]]:
@@ -1232,16 +1221,12 @@ def get_code_class_def(
12321221
d.to_string() for d in self._members
12331222
if d.cls_type is self._this_cls_type
12341223
]
1235-
parent_class_alias = None # type: Optional[str]
12361224
parent = self.get_parent_class()
1237-
if parent is not None:
1238-
# TODO better way to get alias name
1239-
parent_class_alias = parent.__name__
1240-
cdef = CodeSectionClassDef(cu_name, dep_alias, self._code_before_class,
1225+
parent_class_alias = parent.__name__ if parent is not None else None
1226+
return CodeSectionClassDef(cu_name, dep_alias, self._code_before_class,
12411227
self._code_after_class, ext_decls, ec_strs,
12421228
typedef_strs, sc_strs, member_func_decls,
12431229
member_def_strs, parent_class_alias)
1244-
return cdef
12451230

12461231
def get_common_deps(self) -> List["Class"]:
12471232
assert self.graph_inited, "you must build dependency graph before generate code"
@@ -1304,13 +1289,12 @@ def generate_namespace(self, namespace: str):
13041289
if namespace == "":
13051290
return [], []
13061291
namespace_parts = namespace.split(".")
1307-
namespace_before = [] # type: List[str]
1308-
namespace_after = [] # type: List[str]
1292+
namespace_before = ["namespace {} {{".format(p) for p in namespace_parts]
1293+
namespace_after = [
1294+
"}} // namespace {}".format(p) for p in namespace_parts[::-1]
1295+
]
1296+
13091297

1310-
for p in namespace_parts:
1311-
namespace_before.append("namespace {} {{".format(p))
1312-
for p in namespace_parts[::-1]:
1313-
namespace_after.append("}} // namespace {}".format(p))
13141298
return namespace_before, namespace_after
13151299

13161300

@@ -1394,8 +1378,7 @@ def to_block(self) -> Block:
13941378
prefix = code_before_cls + [
13951379
"struct {class_name} {{".format(class_name=self.class_name)
13961380
]
1397-
block = Block("\n".join(prefix), class_contents, "};")
1398-
return block
1381+
return Block("\n".join(prefix), class_contents, "};")
13991382

14001383

14011384
class CodeSectionImpl(CodeSection):
@@ -1438,9 +1421,9 @@ def extract_module_id_of_class(
14381421
relative_path = path.relative_to(Path(root))
14391422
import_parts = list(relative_path.parts)
14401423
import_parts[-1] = relative_path.stem
1424+
elif loader.locate_top_package(path) is None:
1425+
return None
14411426
else:
1442-
if loader.locate_top_package(path) is None:
1443-
return None
14441427
import_parts = loader.try_capture_import_parts(path, None)
14451428
return ".".join(import_parts)
14461429

@@ -1533,35 +1516,35 @@ def _apply_middleware_to_cus(self, uid_to_cu: Dict[str, Class]):
15331516
new_uid_to_cu = OrderedDict() # type: Dict[str, Class]
15341517
for middleware in self.middlewares:
15351518
mw_type = type(middleware)
1536-
if isinstance(middleware, ManualClassGenerator):
1537-
for k, cu in uid_to_cu.items():
1538-
decls_with_meta = [
1539-
] # type: List[Tuple[FunctionDecl, MiddlewareMeta]]
1540-
members_with_meta = [
1541-
] # type: List[Tuple[Member, MiddlewareMeta]]
1542-
# TODO only one meta is allowed
1543-
for decl in cu._function_decls:
1544-
for mw_meta in decl.meta.mw_metas:
1545-
if mw_meta.type is mw_type:
1546-
decls_with_meta.append((decl, mw_meta))
1547-
for member in cu._members:
1548-
for mw_meta in member.mw_metas:
1549-
if mw_meta.type is mw_type:
1550-
members_with_meta.append((member, mw_meta))
1551-
if not decls_with_meta and not members_with_meta:
1552-
continue
1553-
new_pcls = middleware.create_manual_class(cu)
1554-
if new_pcls.namespace is None:
1555-
new_pcls.namespace = cu.namespace + "." + middleware.subnamespace
1556-
for decl, mw_meta in decls_with_meta:
1557-
new_pcls.handle_function_decl(cu, decl, mw_meta)
1558-
for member, mw_meta in members_with_meta:
1559-
new_pcls.handle_member(cu, member, mw_meta)
1560-
uid = new_pcls.namespace + "-" + type(new_pcls).__name__
1561-
new_uid_to_cu[uid] = new_pcls
1562-
else:
1519+
if not isinstance(middleware, ManualClassGenerator):
15631520
raise NotImplementedError
15641521

1522+
for k, cu in uid_to_cu.items():
1523+
decls_with_meta = [
1524+
] # type: List[Tuple[FunctionDecl, MiddlewareMeta]]
1525+
members_with_meta = [
1526+
] # type: List[Tuple[Member, MiddlewareMeta]]
1527+
# TODO only one meta is allowed
1528+
for decl in cu._function_decls:
1529+
for mw_meta in decl.meta.mw_metas:
1530+
if mw_meta.type is mw_type:
1531+
decls_with_meta.append((decl, mw_meta))
1532+
for member in cu._members:
1533+
for mw_meta in member.mw_metas:
1534+
if mw_meta.type is mw_type:
1535+
members_with_meta.append((member, mw_meta))
1536+
if not decls_with_meta and not members_with_meta:
1537+
continue
1538+
new_pcls = middleware.create_manual_class(cu)
1539+
if new_pcls.namespace is None:
1540+
new_pcls.namespace = cu.namespace + "." + middleware.subnamespace
1541+
for decl, mw_meta in decls_with_meta:
1542+
new_pcls.handle_function_decl(cu, decl, mw_meta)
1543+
for member, mw_meta in members_with_meta:
1544+
new_pcls.handle_member(cu, member, mw_meta)
1545+
uid = new_pcls.namespace + "-" + type(new_pcls).__name__
1546+
new_uid_to_cu[uid] = new_pcls
1547+
15651548
def build_graph(self,
15661549
cus: List[Union[Class, ParameterizedClass]],
15671550
root: Optional[Union[str, Path]] = None,

pccm/core/buildmeta.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,10 @@ def _unique_list_keep_order(seq: list):
1212
# https://www.peterbe.com/plog/fastest-way-to-uniquify-a-list-in-python-3.6
1313
# only python 3.7 language std ensure the preserve-order dict
1414
return list(dict.fromkeys(seq))
15-
else:
16-
# https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order
17-
seen = set()
18-
seen_add = seen.add
19-
return [x for x in seq if not (x in seen or seen_add(x))]
15+
# https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order
16+
seen = set()
17+
seen_add = seen.add
18+
return [x for x in seq if not (x in seen or seen_add(x))]
2019

2120

2221
def _merge_compiler_to_flags(this: Dict[str, List[str]],
@@ -66,11 +65,10 @@ def __add__(self, other: "BuildMeta"):
6665
merged_ldflags = _merge_compiler_to_flags(self.compiler_to_ldflags,
6766
other.compiler_to_ldflags)
6867

69-
res = BuildMeta(
68+
return BuildMeta(
7069
self.includes + other.includes, self.libpaths + other.libpaths,
7170
_unique_list_keep_order(self.libraries + other.libraries),
7271
merged_cflags, merged_ldflags)
73-
return res
7472

7573
def __radd__(self, other: "BuildMeta"):
7674
return other.__add__(self)

pccm/core/codegen.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,7 @@ def generate_code(block: Union[Block, str], start_col_offset: int,
3333
return [col_str + l for l in block_lines]
3434
res = [] # type: List[str]
3535
prefix = block.prefix
36-
next_indent = indent
37-
if block.indent is not None:
38-
next_indent = block.indent
36+
next_indent = block.indent if block.indent is not None else indent
3937
if prefix:
4038
prefix_lines = prefix.split("\n")
4139
res.extend([col_str + l for l in prefix_lines])

pccm/graph/__init__.py

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def postorder_traversal(node: Node, node_map: Dict[str, Node]):
8383
if namedio.key not in node_map:
8484
continue
8585
inp = node_map[namedio.key]
86-
if not inp in visited:
86+
if inp not in visited:
8787
next_nodes.append(inp)
8888
ready = False
8989
if ready:
@@ -112,11 +112,10 @@ def _cycle_detection(node_map: Dict[str, Node], node: Node, visited: Set[str],
112112
def cycle_detection(node_map: Dict[str, Node]):
113113
visited = set()
114114
trace = set()
115-
for node in node_map.values():
116-
if node.key not in visited:
117-
if _cycle_detection(node_map, visited, trace):
118-
return True
119-
return False
115+
return any(
116+
node.key not in visited and _cycle_detection(node_map, visited, trace)
117+
for node in node_map.values()
118+
)
120119

121120

122121
class Graph(object):
@@ -177,10 +176,7 @@ def is_source_of(self, lfs: Node, rfs: Node):
177176
def get_sources_of(self, node: Node):
178177
assert not self._has_cycle, "graph must be DAG"
179178
all_sources = set()
180-
stack = []
181-
for inp in node.inputs:
182-
if inp.key in self:
183-
stack.append(self[inp.key])
179+
stack = [self[inp.key] for inp in node.inputs if inp.key in self]
184180
while stack:
185181
n = stack.pop()
186182
if n in all_sources:
@@ -214,10 +210,7 @@ def is_branch_node(self, node: Node):
214210
for io in n.inputs:
215211
if io.key in self:
216212
stack.append(self[io.key])
217-
for s in all_sources:
218-
if s.key in visited:
219-
return True
220-
return False
213+
return any(s.key in visited for s in all_sources)
221214

222215

223216
def create_node(key: str, *inputs: List[NamedIO]):

pccm/middlewares/expose_main.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,12 @@ def create_manual_class(self, cu: Class) -> ManualClass:
6363
return self.singleton
6464

6565
def get_code_units(self) -> List[Class]:
66-
if self.singleton.main_cu is not None:
67-
self.singleton.postprocess()
68-
return [self.singleton]
69-
else:
66+
if self.singleton.main_cu is None:
7067
return []
7168

69+
self.singleton.postprocess()
70+
return [self.singleton]
71+
7272

7373
def mark(func=None):
7474
meta = ExposeMainMeta()

0 commit comments

Comments
 (0)