Skip to content

Commit 9b45d8a

Browse files
committed
chore: fix up the codegen
1 parent f546538 commit 9b45d8a

1 file changed

Lines changed: 50 additions & 53 deletions

File tree

juju/client/facade.py

Lines changed: 50 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def lookup(self, name, version=None):
135135
return versions[version]
136136
return versions[max(versions)]
137137

138-
def getObj(self, name, version=None):
138+
def get_obj(self, name, version=None):
139139
result = self.lookup(name, version)
140140
if result:
141141
obj = result["object"]
@@ -157,10 +157,10 @@ def get(self, name):
157157

158158
return self[refname]
159159

160-
def getRefType(self, ref):
160+
def get_ref_type(self, ref):
161161
return self.get(ref)
162162

163-
def objType(self, obj):
163+
def obj_type(self, obj):
164164
kind = obj.get("type")
165165
if not kind:
166166
raise ValueError("%s has no type" % obj)
@@ -169,18 +169,17 @@ def objType(self, obj):
169169
raise ValueError("%s has type %s" % (obj, kind))
170170
return result
171171

172-
def refType(self, obj):
173-
return self.getRefType(obj["$ref"])
172+
def ref_type(self, obj):
173+
return self.get_ref_type(obj["$ref"])
174174

175175

176176
CLASSES = {}
177177
factories = codegen.Capture()
178178

179179

180180
def booler(v):
181-
if isinstance(v, str):
182-
if v == "false":
183-
return False
181+
if v == "false":
182+
return False
184183
return bool(v)
185184

186185

@@ -247,7 +246,7 @@ def __init__(self, schema, defs):
247246
self.schema = schema
248247
self.defs = defs
249248
if defs:
250-
rtypes = schema.registry.getObj(schema.types[defs])
249+
rtypes = schema.registry.get_obj(schema.types[defs])
251250
if len(rtypes) == 1:
252251
if not self.do_explode(rtypes[0][1]):
253252
for name, rtype in rtypes:
@@ -273,15 +272,15 @@ def do_explode(self, kind):
273272
self.extend(Args(self.schema, kind))
274273
return True
275274

276-
def PyToSchemaMapping(self):
275+
def py_to_schema_mapping(self):
277276
m = {}
278-
for n, rt in self:
277+
for n, _ in self:
279278
m[name_to_py(n)] = n
280279
return m
281280

282-
def SchemaToPyMapping(self):
281+
def schema_to_py_mapping(self):
283282
m = {}
284-
for n, tr in self:
283+
for n, _ in self:
285284
m[n] = name_to_py(n)
286285
return m
287286

@@ -332,15 +331,15 @@ def get_doc(self):
332331

333332

334333
def build_validation(name, instance_type, instance_sub_type, ident=None):
335-
INDENT = ident or " "
336-
source = f"""{INDENT}if {name} is not None and not isinstance({name}, {instance_sub_type}):
337-
{INDENT} raise Exception("Expected {name} to be a {instance_type}, received: {{}}".format(type({name})))
334+
indent = ident or " "
335+
source = f"""{indent}if {name} is not None and not isinstance({name}, {instance_sub_type}):
336+
{indent} raise Exception("Expected {name} to be a {instance_type}, received: {{}}".format(type({name})))
338337
"""
339338
return source
340339

341340

342341
def build_types(schema, capture):
343-
INDENT = " "
342+
indent = " "
344343
for kind in sorted(
345344
(k for k in schema.types if not isinstance(k, str)), key=lambda x: str(x)
346345
):
@@ -368,27 +367,27 @@ def __init__(self{}{}, **unknown_fields):
368367
'''""".format(
369368
name,
370369
# pprint these to get stable ordering across regens
371-
pprint.pformat(args.PyToSchemaMapping(), width=999),
372-
pprint.pformat(args.SchemaToPyMapping(), width=999),
370+
pprint.pformat(args.py_to_schema_mapping(), width=999),
371+
pprint.pformat(args.schema_to_py_mapping(), width=999),
373372
", " if args else "",
374373
args.as_kwargs(),
375-
textwrap.indent(args.get_doc(), INDENT * 2),
374+
textwrap.indent(args.get_doc(), indent * 2),
376375
)
377376
]
378377

379378
if not args:
380-
source.append(f"{INDENT * 2}self.unknown_fields = unknown_fields")
379+
source.append(f"{indent * 2}self.unknown_fields = unknown_fields")
381380
else:
382381
# do the validation first, before setting the variables
383382
for arg in args:
384383
arg_name = name_to_py(arg[0])
385384
arg_type = arg[1]
386385
arg_type_name = strcast(arg_type)
387386
if arg_type in basic_types or arg_type is typing.Any:
388-
source.append(f"{INDENT * 2}{arg_name}_ = {arg_name}")
387+
source.append(f"{indent * 2}{arg_name}_ = {arg_name}")
389388
elif type(arg_type) is typing.TypeVar:
390389
source.append(
391-
f"{INDENT * 2}{arg_name}_ = {arg_type_name}.from_json({arg_name}) if {arg_name} else None"
390+
f"{indent * 2}{arg_name}_ = {arg_type_name}.from_json({arg_name}) if {arg_name} else None"
392391
)
393392
elif typing_inspect.is_generic_type(arg_type) and issubclass(
394393
typing_inspect.get_origin(arg_type), Sequence
@@ -397,27 +396,27 @@ def __init__(self{}{}, **unknown_fields):
397396
value_type = parameters[0] if len(parameters) else None
398397
if type(value_type) is typing.TypeVar:
399398
source.append(
400-
f"{INDENT * 2}{arg_name}_ = [{strcast(value_type)}.from_json(o) for o in {arg_name} or []]"
399+
f"{indent * 2}{arg_name}_ = [{strcast(value_type)}.from_json(o) for o in {arg_name} or []]"
401400
)
402401
else:
403-
source.append(f"{INDENT * 2}{arg_name}_ = {arg_name}")
402+
source.append(f"{indent * 2}{arg_name}_ = {arg_name}")
404403
elif typing_inspect.is_generic_type(arg_type) and issubclass(
405404
typing_inspect.get_origin(arg_type), Mapping
406405
):
407406
parameters = typing_inspect.get_parameters(arg_type)
408407
value_type = parameters[0] if len(parameters) else None
409408
if type(value_type) is typing.TypeVar:
410409
source.append(
411-
f"{INDENT * 2}{arg_name}_ = {{k: {strcast(value_type)}.from_json(v) "
410+
f"{indent * 2}{arg_name}_ = {{k: {strcast(value_type)}.from_json(v) "
412411
f"for k, v in ({arg_name} or dict()).items()}}"
413412
)
414413
else:
415-
source.append(f"{INDENT * 2}{arg_name}_ = {arg_name}")
414+
source.append(f"{indent * 2}{arg_name}_ = {arg_name}")
416415
else:
417-
source.append(f"{INDENT * 2}{arg_name}_ = {arg_name}")
416+
source.append(f"{indent * 2}{arg_name}_ = {arg_name}")
418417
if len(args) > 0:
419418
source.append(
420-
f"\n{INDENT * 2}# Validate arguments against known Juju API types."
419+
f"\n{indent * 2}# Validate arguments against known Juju API types."
421420
)
422421
for arg in args:
423422
arg_name = f"{name_to_py(arg[0])}_"
@@ -426,17 +425,17 @@ def __init__(self{}{}, **unknown_fields):
426425
source.append(
427426
"{}".format(
428427
build_validation(
429-
arg_name, arg_type, arg_sub_type, ident=INDENT * 2
428+
arg_name, arg_type, arg_sub_type, ident=indent * 2
430429
)
431430
)
432431
)
433432

434433
for arg in args:
435434
arg_name = name_to_py(arg[0])
436-
source.append(f"{INDENT * 2}self.{arg_name} = {arg_name}_")
435+
source.append(f"{indent * 2}self.{arg_name} = {arg_name}_")
437436
# Ensure that we take the kwargs (unknown_fields) and put it on the
438437
# Results/Params so we can inspect it.
439-
source.append(f"{INDENT * 2}self.unknown_fields = unknown_fields")
438+
source.append(f"{indent * 2}self.unknown_fields = unknown_fields")
440439

441440
source = "\n".join(source)
442441
capture.clear(name)
@@ -446,7 +445,7 @@ def __init__(self{}{}, **unknown_fields):
446445
print(source)
447446
co = compile(source, __name__, "exec")
448447
ns = _getns(schema)
449-
exec(co, ns)
448+
exec(co, ns) # noqa: S102
450449
cls = ns[name]
451450
CLASSES[name] = cls
452451

@@ -464,7 +463,7 @@ def retspec(schema, defs):
464463
return strcast(defs, False)
465464

466465

467-
def ReturnMapping(cls):
466+
def ReturnMapping(cls): # noqa: N802
468467
# Annotate the method with a return Type
469468
# so the value can be cast
470469
def decorator(f):
@@ -502,12 +501,13 @@ async def wrapper(*args, **kwargs):
502501

503502

504503
def make_func(cls, name, description, params, result, _async=True):
505-
INDENT = " "
504+
indent = " "
506505
args = Args(cls.schema, params)
507-
assignments = []
508-
toschema = args.PyToSchemaMapping()
509-
for arg in args._get_arg_str(False, False):
510-
assignments.append(f"{INDENT}_params['{toschema[arg]}'] = {arg}")
506+
toschema = args.py_to_schema_mapping()
507+
assignments = [
508+
f"{indent}_params['{toschema[arg]}'] = {arg}"
509+
for arg in args._get_arg_str(False, False)
510+
]
511511
assignments = "\n".join(assignments)
512512
res = retspec(cls.schema, result)
513513
source = """
@@ -544,13 +544,13 @@ def make_func(cls, name, description, params, result, _async=True):
544544
res=res,
545545
validation=args.as_validation(),
546546
rettype=result.__name__ if result else None,
547-
docstring=textwrap.indent(doc_string, INDENT),
547+
docstring=textwrap.indent(doc_string, indent),
548548
cls=cls,
549549
assignments=assignments,
550550
_await="await " if _async else "",
551551
)
552552
ns = _getns(cls.schema)
553-
exec(fsource, ns)
553+
exec(fsource, ns) # noqa: S102
554554
func = ns[name]
555555
return func, fsource
556556

@@ -572,7 +572,7 @@ async def rpc(self, msg):
572572
573573
"""
574574
ns = _getns(cls.schema)
575-
exec(source, ns)
575+
exec(source, ns) # noqa: S102
576576
func = ns["rpc"]
577577
return func, source
578578

@@ -671,7 +671,7 @@ def _parse_nested_list_entry(expr, result_dict):
671671
# this is a simple entry
672672
result_dict[expr] = ""
673673
elif isinstance(expr, dict):
674-
for _, v in expr.items():
674+
for v in expr.values():
675675
_parse_nested_list_entry(v, result_dict)
676676
elif isinstance(expr, list):
677677
for v in expr:
@@ -716,9 +716,6 @@ def to_json(self):
716716
def __contains__(self, key):
717717
return key in self._toPy
718718

719-
def get(self, key, default=None):
720-
return self[key] if key in self else default
721-
722719
# treat subscript gets as JSON representation
723720
def __getitem__(self, key):
724721
attr = self._toPy[key]
@@ -773,7 +770,7 @@ def build_definitions(self):
773770
for d, definition in definitions.items():
774771
node = self.build_object(definition, d)
775772
self.registry.register(d, self.version, node)
776-
self.types.getRefType(d)
773+
self.types.get_ref_type(d)
777774

778775
def build_object(self, node, name=None):
779776
# we don't need to build types recursively here
@@ -790,23 +787,23 @@ def build_object(self, node, name=None):
790787
for p in sorted(props):
791788
prop = props[p]
792789
if "$ref" in prop:
793-
add((p, self.types.refType(prop)))
790+
add((p, self.types.ref_type(prop)))
794791
else:
795792
kind = prop["type"]
796793
if kind == "array":
797794
add((p, self.build_array(prop)))
798795
elif kind == "object":
799796
struct.extend(self.build_object(prop, p))
800797
else:
801-
add((p, self.types.objType(prop)))
798+
add((p, self.types.obj_type(prop)))
802799
if pprops:
803800
if ".*" not in pprops:
804801
raise ValueError(
805802
"Cannot handle actual pattern in patternProperties %s" % pprops
806803
)
807804
pprop = pprops[".*"]
808805
if "$ref" in pprop:
809-
add((name, Mapping[str, self.types.refType(pprop)]))
806+
add((name, Mapping[str, self.types.ref_type(pprop)]))
810807
return struct
811808
ppkind = pprop["type"]
812809
if ppkind == "array":
@@ -822,21 +819,21 @@ def build_object(self, node, name=None):
822819
def build_array(self, obj):
823820
# return a sequence from an array in the schema
824821
if "$ref" in obj:
825-
return Sequence[self.types.refType(obj)]
822+
return Sequence[self.types.ref_type(obj)]
826823
else:
827824
kind = obj.get("type")
828825
if kind and kind == "array":
829826
items = obj["items"]
830827
return self.build_array(items)
831828
else:
832-
return Sequence[self.types.objType(obj)]
829+
return Sequence[self.types.obj_type(obj)]
833830

834831

835832
def _getns(schema):
836833
ns = {"Type": Type, "typing": typing, "ReturnMapping": ReturnMapping}
837834
# Copy our types into the globals of the method
838835
for facade in schema.registry:
839-
ns[facade] = schema.registry.getObj(facade)
836+
ns[facade] = schema.registry.get_obj(facade)
840837
return ns
841838

842839

0 commit comments

Comments
 (0)