Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Rewrites len(..) == 0 into not ..#51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
sdpython merged 2 commits intomainfromlen
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion_unittests/ut_light_api/test_light_api.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -138,7 +138,7 @@ def list_ops_missing(self, n_inputs):
methods.append("")
new_missing.append(m)
text = "\n".join(methods)
iflen(new_missing) > 0:
if new_missing:
raise AssertionError(
f"n_inputs={n_inputs}: missing method for operators "
f"{new_missing}\n{text}"
Expand Down
2 changes: 1 addition & 1 deletion_unittests/ut_validation/test_f8.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -344,7 +344,7 @@ def test_search_float32_into_fe5m2(self):
add=value
else:
add=v-value
iflen(w)>0:
ifw:
raiseAssertionError(
f"A warning was thrown for v={v}, "
f"value={value}, w={w[0]}."
Expand Down
4 changes: 2 additions & 2 deletions_unittests/ut_xrun_doc/test_documentation_examples.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ def import_source(module_file_path, module_name):
classTestDocumentationExamples(ExtTestCase):
defrun_test(self,fold:str,name:str,verbose=0)->int:
ppath=os.environ.get("PYTHONPATH","")
iflen(ppath)==0:
ifnotppath:
os.environ["PYTHONPATH"]=ROOT
elifROOTnotinppath:
sep=";"ifis_windows()else":"
Expand All@@ -42,7 +42,7 @@ def run_test(self, fold: str, name: str, verbose=0) -> int:
res=p.communicate()
out,err=res
st=err.decode("ascii",errors="ignore")
iflen(st)>0and"Traceback"inst:
ifstand"Traceback"inst:
if'"dot" not found in path.'inst:
# dot not installed, this part
# is tested in onnx framework
Expand Down
6 changes: 2 additions & 4 deletionsonnx_array_api/ext_test_case.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -226,9 +226,7 @@ def assertRaise(self, fct: Callable, exc_type: Exception):
raiseAssertionError("No exception was raised.")

defassertEmpty(self,value:Any):
ifvalueisNone:
return
iflen(value)==0:
ifnotvalue:
return
raiseAssertionError(f"value is not empty:{value!r}.")

Expand All@@ -240,7 +238,7 @@ def assertNotEmpty(self, value: Any):
ifvalueisNone:
raiseAssertionError(f"value is empty:{value!r}.")
ifisinstance(value, (list,dict,tuple,set)):
iflen(value)==0:
ifvalue:
raiseAssertionError(f"value is empty:{value!r}.")

defassertStartsWith(self,prefix:str,full:str):
Expand Down
2 changes: 1 addition & 1 deletiononnx_array_api/light_api/emitter.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -85,7 +85,7 @@ def render_attribute_value(self, value: Any) -> Tuple[List[str], str]:
ifisinstance(v,str):
return [],f"{v!r}"
ifisinstance(v,np.ndarray):
iflen(v.shape)==0:
ifnotv.shape:
return [],str(v)
iflen(v.shape)==1:
ifvalue[0].typein (
Expand Down
2 changes: 1 addition & 1 deletiononnx_array_api/light_api/translate.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -51,7 +51,7 @@ def export(self, as_str, single_line: bool = False) -> Union[str, List[str]]:
else:
raiseValueError(f"Unexpected type{type(self.proto_)} for proto.")

iflen(sparse_initializers)!=0:
ifsparse_initializers:
raiseNotImplementedError("Sparse initializer not supported yet.")

rows.extend(
Expand Down
2 changes: 1 addition & 1 deletiononnx_array_api/npx/npx_graph_builder.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -919,7 +919,7 @@ def to_onnx(
[(var,i,None)foriinrange(var.n_var_outputs)]
)

iflen(possible_types)>0:
ifpossible_types:
# converts possibles types into a dictionary
map_types= {}
forvar,i,dtinpossible_types:
Expand Down
4 changes: 2 additions & 2 deletionsonnx_array_api/npx/npx_helper.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -47,7 +47,7 @@ def _process_attributes(attributes):
nodes= []
modified=False
fornodeingraph.node:
iflen(set(node.input)&set_rep)==0:
ifnot(set(node.input)&set_rep):
modified=True
new_inputs= [replacements.get(i,i)foriinnode.input]
atts=_process_attributes(node.attribute)ornode.attribute
Expand All@@ -66,7 +66,7 @@ def _process_attributes(attributes):
ifnotmodified:
returnNone

iflen(set(i.nameforiingraph.input)&set_rep)==0:
ifnot(set(i.nameforiingraph.input)&set_rep):
returnmake_graph(nodes,graph.name,graph.input,graph.output)

new_inputs= []
Expand Down
12 changes: 6 additions & 6 deletionsonnx_array_api/npx/npx_jit_eager.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -253,7 +253,7 @@ def to_jit(self, *values, **kwargs):
"""
self.info("+", "to_jit", args=values, kwargs=kwargs)
annotations = self.f.__annotations__
iflen(annotations) > 0:
if annotations:
input_to_kwargs = {}
kwargs_to_input = {}
names = list(annotations.keys())
Expand DownExpand Up@@ -352,10 +352,10 @@ def to_jit(self, *values, **kwargs):
if iname in constraints
]
names = [i.name for i in inputs]
iflen(new_kwargs) > 0:
if new_kwargs:
# An attribute is not named in the numpy API
# but is the ONNX definition.
iflen(kwargs) == 0:
ifnot kwargs:
kwargs = new_kwargs
else:
kwargs = kwargs.copy()
Expand All@@ -375,13 +375,13 @@ def to_jit(self, *values, **kwargs):
target_opsets=self.target_opsets,
ir_version=self.ir_version,
)
iflen(values) > 0andlen(values[0].shape) == 0:
if valuesandnotvalues[0].shape:
inps = onx.graph.input[0]
shape = []
for d in inps.type.tensor_type.shape.dim:
v = d.dim_value if d.dim_value > 0 else d.dim_param
shape.append(v)
iflen(shape) != 0:
if shape:
raise RuntimeError(
f"Shape mismatch, values[0]={values[0]} "
f"and inputs={onx.graph.input}."
Expand DownExpand Up@@ -441,7 +441,7 @@ def move_input_to_kwargs(
f"self.input_to_kwargs_ is not initialized for function {self.f} "
f"from module {self.f.__module__!r}."
)
iflen(self.input_to_kwargs_) == 0:
ifnotself.input_to_kwargs_:
return values, kwargs
new_values = []
new_kwargs = kwargs.copy()
Expand Down
6 changes: 3 additions & 3 deletionsonnx_array_api/npx/npx_numpy_tensors.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -220,7 +220,7 @@ def __bool__(self):
)
ifself.shape== (0,):
returnFalse
iflen(self.shape)!=0:
ifself.shape:
warnings.warn(
f"Conversion to bool only works for scalar, not for{self!r}, "
f"bool(...)={bool(self._tensor)}."
Expand All@@ -233,7 +233,7 @@ def __bool__(self):

def__int__(self):
"Implicit conversion to int."
iflen(self.shape)!=0:
ifself.shape:
raiseValueError(
f"Conversion to bool only works for scalar, not for{self!r}."
)
Expand All@@ -255,7 +255,7 @@ def __int__(self):

def__float__(self):
"Implicit conversion to float."
iflen(self.shape)!=0:
ifself.shape:
raiseValueError(
f"Conversion to bool only works for scalar, not for{self!r}."
)
Expand Down
8 changes: 4 additions & 4 deletionsonnx_array_api/npx/npx_var.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -174,7 +174,7 @@ def to_onnx(
f"Mismatch number of outputs, expecting {len(outputs)}, "
f"got ({len(onx.output)})."
)
iflen(g.functions_) > 0:
if g.functions_:
return [g.functions_, onx]
return onx

Expand DownExpand Up@@ -1020,7 +1020,7 @@ def __getitem__(self, index: Any) -> "Var":

if not isinstance(index, tuple):
index = (index,)
eliflen(index) == 0:
elifnot index:
# The array contains a scalar and it needs to be returned.
return var(self, op="Identity")

Expand DownExpand Up@@ -1091,7 +1091,7 @@ def __getitem__(self, index: Any) -> "Var":
starts = np.array(starts, dtype=np.int64)
axes = np.array(axes, dtype=np.int64)

iflen(needs_shape) > 0:
if needs_shape:
shape = self.shape
conc = []
for e in ends:
Expand All@@ -1116,7 +1116,7 @@ def __getitem__(self, index: Any) -> "Var":
sliced_args.append(steps)
sliced_args_cst = [v if isinstance(v, Var) else cst(v) for v in sliced_args]
sliced = var(self.self_var, *sliced_args_cst, op="Slice")
iflen(axis_squeeze) > 0:
if axis_squeeze:
return var(
sliced,
cst(np.array(axis_squeeze, dtype=np.int64)),
Expand Down
5 changes: 1 addition & 4 deletionsonnx_array_api/plotting/_helper.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -120,10 +120,7 @@ def get_tensor_shape(obj):
for d in obj.tensor_type.shape.dim:
v = d.dim_value if d.dim_value > 0 else d.dim_param
shape.append(v)
if len(shape) == 0:
shape = None
else:
shape = list(None if s == 0 else s for s in shape)
shape = None if not shape else list(None if s == 0 else s for s in shape)
return shape


Expand Down
6 changes: 3 additions & 3 deletionsonnx_array_api/plotting/dot_plot.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -242,7 +242,7 @@ def dot_label(text):
fornodeinnodes:
exp.append("")
foroutinnode.output:
iflen(out)>0andoutnotininter_vars:
ifoutandoutnotininter_vars:
inter_vars[out]=out
sh=shapes.get(out,"")
ifsh:
Expand DownExpand Up@@ -318,7 +318,7 @@ def dot_label(text):
f"{dot_name(subprefix)}{dot_name(inp2.name)};"
)
forout1,out2inzip(body.output,node.output):
iflen(out2)==0:
ifnotout2:
# Empty output, it cannot be used.
continue
exp.append(
Expand DownExpand Up@@ -346,7 +346,7 @@ def dot_label(text):
f"{dot_name(prefix)}{dot_name(node.name)};"
)
foroutinnode.output:
iflen(out)==0:
ifnotout:
# Empty output, it cannot be used.
continue
exp.append(
Expand Down
14 changes: 7 additions & 7 deletionsonnx_array_api/plotting/text_plot.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -75,7 +75,7 @@ def append_target(self, tid, weight):
defprocess_node(self):
"node to string"
ifself.nodes_modes=="LEAF":
iflen(self.targets)==0:
ifnotself.targets:
text=f"{self.true_false}f"
eliflen(self.targets)==1:
t=self.targets[0]
Expand DownExpand Up@@ -264,7 +264,7 @@ def _append_succ_pred_s(
unknown.add(i)
foriinn.output:
known[i]=n
iflen(unknown)>0:
ifunknown:
# These inputs are coming from the graph below.
fornameinunknown:
successors[name].append(parent_node_name)
Expand DownExpand Up@@ -402,7 +402,7 @@ def _find_sequence(node_name, known, done):
% (k,",".join(sequences[k]),list(sequences))
)

iflen(sequences)==0:
ifnotsequences:
raiseRuntimeError(# pragma: no cover
"Unexpected empty sequence (len(possibles)=%d, "
"len(done)=%d, len(nodes)=%d). This is usually due to "
Expand All@@ -417,7 +417,7 @@ def _find_sequence(node_name, known, done):
# if the sequence of successors is longer
best=k
eliflen(v)==len(sequences[best]):
iflen(new_nodes)>0:
ifnew_nodes:
# then choose the next successor sharing input with
# previous output
so=set(new_nodes[-1].output)
Expand DownExpand Up@@ -808,7 +808,7 @@ def str_node(indent, node):
val=".%d"%att.type
atts.append(f"{att.name}={val}")
inputs=list(node.input)
iflen(atts)>0:
ifatts:
inputs.extend(atts)
ifnode.domainin ("","ai.onnx.ml"):
domain=""
Expand DownExpand Up@@ -917,7 +917,7 @@ def str_node(indent, node):
indent=previous_indent
else:
inds= [indents.get(i,0)foriinnode.inputifinotininit_names]
iflen(inds)==0:
ifnotinds:
indent=0
else:
mi=min(inds)
Expand All@@ -929,7 +929,7 @@ def str_node(indent, node):
)
add_break=True
ifnotadd_breakandprevious_outisnotNone:
iflen(set(node.input)&previous_out)==0:
ifnot(set(node.input)&previous_out):
ifverbose:
print(f"[onnx_simple_text_plot] break3{node.op_type}")
add_break=True
Expand Down
4 changes: 2 additions & 2 deletionsonnx_array_api/profiling.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -71,7 +71,7 @@ def get_root(self):
def _get_root(node, stor=None):
if stor is not None:
stor.append(node)
iflen(node.called_by) == 0:
ifnotnode.called_by:
return node
if len(node.called_by) == 1:
return _get_root(node.called_by[0], stor=stor)
Expand DownExpand Up@@ -383,7 +383,7 @@ def walk(node, roots_keys, indent=0):
continue
child[key] = walk(n, roots_key, indent + 1)

iflen(child) > 0:
if child:
mx = max(_[0] for _ in child)
dg = int(math.log(mx) / math.log(10) + 1.5)
form = f"%-{dg}d-%s"
Expand Down
2 changes: 1 addition & 1 deletiononnx_array_api/reference/ops/op_constant_of_shape.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ class ConstantOfShape(OpRun):
def_process(value):
cst=value[0]ifisinstance(value,np.ndarray)andvalue.size>0elsevalue
ifisinstance(value,np.ndarray):
iflen(value.shape)==0:
ifnotvalue.shape:
cst=value
elifvalue.size>0:
cst=value.ravel()[0]
Expand Down
2 changes: 1 addition & 1 deletiononnx_array_api/validation/tools.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -49,7 +49,7 @@ def randomize_proto(
doc_string=onx.doc_string,
opset_imports=list(onx.opset_import),
)
iflen(onx.metadata_props) > 0:
if onx.metadata_props:
values = {p.key: p.value for p in onx.metadata_props}
set_model_props(onnx_model, values)
return onnx_model
Expand Down
4 changes: 2 additions & 2 deletionssetup.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,7 +18,7 @@
requirements = f.read().strip(" \n\r\t").split("\n")
except FileNotFoundError:
requirements = []
iflen(requirements) == 0 or requirements == [""]:
ifnot requirements or requirements == [""]:
requirements = ["numpy", "scipy", "onnx"]

try:
Expand All@@ -34,7 +34,7 @@
for _ in [_.strip("\r\n ") for _ in f.readlines()]
if _.startswith("__version__")
]
iflen(line) > 0:
if line:
version_str = line[0].split("=")[1].strip('" ')


Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp