Skip to content

Commit cf8011b

Browse files
committed
fix a million flake8 errors
1 parent 6947ba4 commit cf8011b

File tree

5 files changed

+35
-55
lines changed

5 files changed

+35
-55
lines changed

examples/document.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import modelspec
22
from modelspec import field, instance_of, optional
33
from modelspec.base_types import Base
4-
from typing import List, Optional, Union
4+
from typing import List
55

66
# Example showing how to create a model of a document and use it to create/serialize instances
77

src/modelspec/base_types.py

Lines changed: 23 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,7 @@
88

99
from typing import (
1010
Optional,
11-
List,
12-
Dict,
13-
Any,
14-
Union,
1511
Tuple,
16-
Type,
17-
TypeVar,
18-
Callable,
19-
Iterable,
2012
)
2113

2214
from docstring_parser import parse
@@ -29,14 +21,9 @@
2921

3022
from typing import Union, List, Dict, Any
3123

32-
from attr import has, field, fields
33-
from attr.validators import optional, instance_of, in_
34-
35-
from cattr.gen import make_dict_unstructure_fn, make_dict_structure_fn, override
24+
from cattr.gen import make_dict_unstructure_fn, override
3625
from cattr.preconf.pyyaml import make_converter as make_yaml_converter
3726

38-
39-
from collections import OrderedDict
4027
from tabulate import tabulate
4128

4229
verbose = False
@@ -48,7 +35,7 @@
4835

4936
class EvaluableExpression(str):
5037
"""
51-
EvaluableExpression is a string that can be evaluated to a value during MDF execution. This class inherits from
38+
EvaluableExpression is a string that can be evaluated to a value during modelspec execution. This class inherits from
5239
str, so it can be used as a string.
5340
"""
5441

@@ -139,13 +126,13 @@ def from_dict(cls, d: Dict[str, Any]) -> "Base":
139126

140127
@classmethod
141128
def from_json(cls, json_str: str) -> "Base":
142-
"""Instantiate an MDF object from a JSON string"""
129+
"""Instantiate an modelspec object from a JSON string"""
143130
return cls.from_dict(json.loads(json_str))
144131

145132
def to_json_file(
146133
self, filename: Optional[str] = None, include_metadata: bool = True
147134
) -> str:
148-
"""Convert the MDF model to JSON format and save to a file.
135+
"""Convert the modelspec model to JSON format and save to a file.
149136
150137
.. note::
151138
JSON is standard file format uses human-readable text to store and transmit data objects consisting of
@@ -180,10 +167,10 @@ def to_yaml(self, include_metadata: bool = True) -> str:
180167
return yaml.dump(yaml_converter.unstructure(self.to_dict()), sort_keys=False)
181168

182169
def to_yaml_file(self, filename: str, include_metadata: bool = True) -> str:
183-
"""Convert file in MDF format to yaml format
170+
"""Convert modelspec format to yaml format
184171
185172
Args:
186-
filename: File in MDF format (Filename extension: .mdf )
173+
filename: File in modelspec format (Filename extension: .yaml )
187174
include_metadata: Contains contact information, citations, acknowledgements, pointers to sample data,
188175
benchmark results, and environments in which the specified model was originally implemented
189176
Returns:
@@ -203,52 +190,52 @@ def to_yaml_file(self, filename: str, include_metadata: bool = True) -> str:
203190
return filename
204191

205192
@classmethod
206-
def from_file(cls, filename: str) -> "Model":
193+
def from_file(cls, filename: str) -> "Base":
207194
"""
208-
Create a :class:`.Model` from its representation stored in a file. Auto-detect the correct deserialization code
195+
Create a :class:`.Base` from its representation stored in a file. Auto-detect the correct deserialization code
209196
based on file extension. Currently supported formats are; JSON(.json) and YAML (.yaml or .yml)
210197
211198
Args:
212199
filename: The name of the file to load.
213200
214201
Returns:
215-
An MDF :class:`.Model` for this file.
202+
An modelspec :class:`.Base` for this file.
216203
"""
217204
if filename.endswith(".yaml") or filename.endswith(".yml"):
218205
return cls.from_yaml_file(filename)
219206
elif filename.endswith(".json"):
220207
return cls.from_json_file(filename)
221208
else:
222209
raise ValueError(
223-
f"Cannot auto-detect MDF serialization format from filename ({filename}). The filename "
210+
f"Cannot auto-detect modelspec serialization format from filename ({filename}). The filename "
224211
f"must have one of the following extensions: .json, .yml, or .yaml."
225212
)
226213

227214
@classmethod
228-
def from_json_file(cls, filename: str) -> "Model":
215+
def from_json_file(cls, filename: str) -> "Base":
229216
"""
230-
Create a :class:`.Model` from its JSON representation stored in a file.
217+
Create a :class:`.Base` from its JSON representation stored in a file.
231218
232219
Args:
233220
filename: The file from which to load the JSON data.
234221
235222
Returns:
236-
An MDF :class:`.Model` for this JSON
223+
An modelspec :class:`.Base` for this JSON
237224
"""
238225
with open(filename) as infile:
239226
d = json.load(infile)
240227
return cls.from_dict(d)
241228

242229
@classmethod
243-
def from_yaml_file(cls, filename: str) -> "Model":
230+
def from_yaml_file(cls, filename: str) -> "Base":
244231
"""
245-
Create a :class:`.Model` from its YAML representation stored in a file.
232+
Create a :class:`.Base` from its YAML representation stored in a file.
246233
247234
Args:
248235
filename: The file from which to load the YAML data.
249236
250237
Returns:
251-
An MDF :class:`.Model` for this YAML
238+
An modelspec :class:`.Base` for this YAML
252239
"""
253240
with open(filename) as infile:
254241
d = yaml.safe_load(infile)
@@ -269,7 +256,7 @@ def get_child(self, id: str, type_: str) -> Any:
269256
"""
270257

271258
# We can't find the container for this type of child object.
272-
if not type_ in [f.name for f in attr.fields(self.__class__)]:
259+
if type_ not in [f.name for f in attr.fields(self.__class__)]:
273260
return None
274261

275262
children = self.__getattribute__(type_)
@@ -462,7 +449,7 @@ def _is_base_type(
462449
or (can_be_list and value == list)
463450
or (can_be_dict and value == dict)
464451
or (can_be_ndarray and value == numpy.ndarray)
465-
or (can_be_none and value is type(None))
452+
or (can_be_none and value is None)
466453
or (can_be_eval_expr and cls._is_evaluable_expression(value))
467454
or value == Union
468455
)
@@ -485,7 +472,6 @@ def _type_to_str(type_: Any) -> str:
485472

486473
# If its a Generic type
487474
elif get_origin(type_) is not None:
488-
collection_arg = None
489475
if get_origin(type_) == list and len(get_args(type_)) > 0:
490476
return Base._type_to_str(get_args(type_)[0])
491477
elif get_origin(type_) == dict and len(get_args(type_)) > 0:
@@ -532,7 +518,7 @@ def _cls_generate_documentation(cls, format: str = MARKDOWN_FORMAT):
532518
rst_url_format = "`%s <%s>`_"
533519

534520
def insert_links(text, format=MARKDOWN_FORMAT):
535-
if not "_" in text:
521+
if "_" not in text:
536522
return text
537523
if '"' in text:
538524
return text # Assume it's a quoted string containing an underscore...
@@ -811,13 +797,13 @@ def f(obj_list):
811797
return f
812798

813799

814-
def _structure_list_mdfbase(cl):
800+
def _structure_list_base(cl):
815801
"""Deserialize list of dict of Base objects as a list if all of their elements have ids"""
816-
mdf_class = get_args(cl)[0]
802+
base_class = get_args(cl)[0]
817803

818804
def f(obj_dict, t):
819805
try:
820-
obj_list = [converter.structure(v, mdf_class) for v in obj_dict.values()]
806+
obj_list = [converter.structure(v, base_class) for v in obj_dict.values()]
821807

822808
# Give each object the id that is its key in the dict.
823809
for id, obj in zip(obj_dict.keys(), obj_list):
@@ -845,7 +831,7 @@ def _is_list_base(cl):
845831
_base_unstruct_hook_factory,
846832
)
847833

848-
converter.register_structure_hook_factory(_is_list_base, _structure_list_mdfbase)
834+
converter.register_structure_hook_factory(_is_list_base, _structure_list_base)
849835
converter.register_structure_hook_factory(
850836
lambda cl: issubclass(cl, Base) and "id" in [a.name for a in fields(cl)],
851837
_base_struct_hook_factory,

src/modelspec/utils.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
from modelspec import *
21
import sys
32
import json
43
import yaml
54
import os
65
import math
76
import numpy as np
87

9-
from modelspec.base_types import print_v, print_
8+
from modelspec.base_types import print_
109
from modelspec.base_types import EvaluableExpression
1110

1211
verbose = False
@@ -118,7 +117,6 @@ def _parse_attributes(dict_format, to_build):
118117

119118
if type_to_use == EvaluableExpression:
120119
vv = {}
121-
dd = _parse_attributes(value, vv)
122120
to_build.__setattr__(key, vv)
123121
else:
124122
ff = type_to_use()
@@ -133,9 +131,9 @@ def _parse_attributes(dict_format, to_build):
133131
elif type(value) == list:
134132
type_to_use = to_build.allowed_children[key][1]
135133

136-
for l in value:
134+
for vl in value:
137135
ff = type_to_use()
138-
ff = _parse_element(l, ff)
136+
ff = _parse_element(vl, ff)
139137
exec("to_build.%s.append(ff)" % key)
140138
else:
141139
type_to_use = to_build.allowed_fields[key][1]
@@ -150,7 +148,7 @@ def locate_file(f, base_dir):
150148
"""
151149
Utility method for finding full path to a filename as string
152150
"""
153-
if base_dir == None:
151+
if base_dir is None:
154152
return f
155153
file_name = os.path.join(base_dir, f)
156154
real = os.path.realpath(file_name)
@@ -325,5 +323,4 @@ def parse_list_like(list_str):
325323
except:
326324
pass
327325
if "[" in list_str:
328-
l = eval(list_str)
329-
return l
326+
return eval(list_str)

tests/test_base.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def test_save_load_json(tmp_path):
160160
filenamey = str(tmp_path / f"{net.id}.yaml")
161161
# net.id = net.id+'_yaml'
162162
net.to_yaml_file(filenamey)
163-
from modelspec.utils import load_json, load_yaml, _parse_element
163+
from modelspec.utils import load_json, load_yaml
164164

165165
dataj = load_json(filenamej)
166166
print_v("Loaded network specification from %s" % filenamej)
@@ -174,7 +174,6 @@ def test_save_load_json(tmp_path):
174174
nety = NewNetwork.from_dict(datay)
175175
str_nety = str(nety)
176176

177-
verbose = False
178177
print("----- Before -----")
179178
print(str_orig)
180179
print("----- After via %s -----" % filenamej)
@@ -295,7 +294,7 @@ class Document(Base):
295294
doc.sections.append(a)
296295
doc.sections.append(Section(id="Chapter 1"))
297296

298-
json_str = doc.to_json()
299-
yaml_str = doc.to_yaml()
300-
doc_md = doc.generate_documentation(format="markdown")
301-
doc_rst = doc.generate_documentation(format="rst")
297+
doc.to_json()
298+
doc.to_yaml()
299+
doc.generate_documentation(format="markdown")
300+
doc.generate_documentation(format="rst")

tests/test_utils.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
from modelspec.base_types import *
2-
from modelspec.utils import *
3-
1+
from modelspec.utils import evaluate
42
from modelspec.utils import _val_info
53

64
import numpy as np

0 commit comments

Comments
 (0)