Run black reformatter on code

This commit is contained in:
Griatch 2022-02-08 13:03:52 +01:00
parent 4582eb4085
commit bd3e31bf3c
178 changed files with 4511 additions and 3385 deletions

View file

@ -262,7 +262,8 @@ def _validate_prototype(prototype):
def _format_protfuncs():
out = []
sorted_funcs = [
(key, func) for key, func in sorted(protlib.FUNC_PARSER.callables.items(), key=lambda tup: tup[0])
(key, func)
for key, func in sorted(protlib.FUNC_PARSER.callables.items(), key=lambda tup: tup[0])
]
for protfunc_name, protfunc in sorted_funcs:
out.append(
@ -2113,8 +2114,9 @@ def _apply_diff(caller, **kwargs):
objects = kwargs["objects"]
back_node = kwargs["back_node"]
diff = kwargs.get("diff", None)
num_changed = spawner.batch_update_objects_with_prototype(prototype, diff=diff, objects=objects,
caller=caller)
num_changed = spawner.batch_update_objects_with_prototype(
prototype, diff=diff, objects=objects, caller=caller
)
caller.msg("|g{num} objects were updated successfully.|n".format(num=num_changed))
return back_node
@ -2354,7 +2356,7 @@ def node_apply_diff(caller, **kwargs):
def node_prototype_save(caller, **kwargs):
"""Save prototype to disk """
"""Save prototype to disk"""
# these are only set if we selected 'yes' to save on a previous pass
prototype = kwargs.get("prototype", None)
# set to True/False if answered, None if first pass

View file

@ -50,16 +50,20 @@ def protfunc_callable_protkey(*args, **kwargs):
prot_value = prototype[fieldname]
else:
# check if it's an attribute
for attrtuple in prototype.get('attrs', []):
for attrtuple in prototype.get("attrs", []):
if attrtuple[0] == fieldname:
prot_value = attrtuple[1]
break
else:
raise AttributeError(f"{fieldname} not found in prototype\n{prototype}\n"
"(neither as prototype-field or as an Attribute")
raise AttributeError(
f"{fieldname} not found in prototype\n{prototype}\n"
"(neither as prototype-field or as an Attribute"
)
if callable(prot_value):
raise RuntimeError(f"Error in prototype\n{prototype}\n$protkey can only reference static "
f"values/attributes (found {prot_value})")
raise RuntimeError(
f"Error in prototype\n{prototype}\n$protkey can only reference static "
f"values/attributes (found {prot_value})"
)
try:
return funcparser.funcparser_callable_eval(prot_value, **kwargs)
except funcparser.ParsingError:

View file

@ -131,8 +131,9 @@ def homogenize_prototype(prototype, custom_keys=None):
for attr in attrs:
# attrs must be on form [(key, value, category, lockstr)]
if not is_iter(attr):
logger.log_error("Prototype's 'attr' field must "
f"be a list of tuples: {prototype}")
logger.log_error(
"Prototype's 'attr' field must " f"be a list of tuples: {prototype}"
)
elif attr:
nattr = len(attr)
if nattr == 1:
@ -147,14 +148,15 @@ def homogenize_prototype(prototype, custom_keys=None):
elif key == "prototype_parent":
# homogenize any prototype-parents embedded directly as dicts
protparents = prototype.get('prototype_parent', [])
protparents = prototype.get("prototype_parent", [])
if isinstance(protparents, dict):
protparents = [protparents]
for parent in make_iter(protparents):
if isinstance(parent, dict):
# recursively homogenize directly embedded prototype parents
homogenized_parents.append(
homogenize_prototype(parent, custom_keys=custom_keys))
homogenize_prototype(parent, custom_keys=custom_keys)
)
else:
# normal prototype-parent names are added as-is
homogenized_parents.append(parent)
@ -170,7 +172,7 @@ def homogenize_prototype(prototype, custom_keys=None):
if homogenized_tags:
homogenized["tags"] = homogenized_tags
if homogenized_parents:
homogenized['prototype_parent'] = homogenized_parents
homogenized["prototype_parent"] = homogenized_parents
# add required missing parts that had defaults before
@ -190,6 +192,7 @@ def homogenize_prototype(prototype, custom_keys=None):
# module/dict-based prototypes
def load_module_prototypes(*mod_or_prototypes, override=True):
"""
Load module prototypes. Also prototype-dicts passed directly to this function are considered
@ -233,12 +236,16 @@ def load_module_prototypes(*mod_or_prototypes, override=True):
# prototype dicts that must have 'prototype_key' set.
for prot in prototype_list:
if not isinstance(prot, dict):
logger.log_err(f"Prototype read from {mod}.PROTOTYPE_LIST "
f"is not a dict (skipping): {prot}")
logger.log_err(
f"Prototype read from {mod}.PROTOTYPE_LIST "
f"is not a dict (skipping): {prot}"
)
continue
elif "prototype_key" not in prot:
logger.log_err(f"Prototype read from {mod}.PROTOTYPE_LIST "
f"is missing the 'prototype_key' (skipping): {prot}")
logger.log_err(
f"Prototype read from {mod}.PROTOTYPE_LIST "
f"is missing the 'prototype_key' (skipping): {prot}"
)
continue
prots.append((prot["prototype_key"], homogenize_prototype(prot)))
else:
@ -270,7 +277,8 @@ def load_module_prototypes(*mod_or_prototypes, override=True):
{
"prototype_key": actual_prot_key,
"prototype_desc": (
prototype["prototype_desc"] if "prototype_desc" in prototype else (mod or "N/A")),
prototype["prototype_desc"] if "prototype_desc" in prototype else (mod or "N/A")
),
"prototype_locks": (
prototype["prototype_locks"]
if "prototype_locks" in prototype
@ -292,9 +300,11 @@ def load_module_prototypes(*mod_or_prototypes, override=True):
if isinstance(mod_or_dict, dict):
# a single prototype; we must make sure it has its key
prototype_key = mod_or_dict.get('prototype_key')
prototype_key = mod_or_dict.get("prototype_key")
if not prototype_key:
raise ValidationError(f"The prototype {mod_or_prototype} does not contain a 'prototype_key'")
raise ValidationError(
f"The prototype {mod_or_prototype} does not contain a 'prototype_key'"
)
prots = [(prototype_key, mod_or_dict)]
mod = None
else:
@ -307,7 +317,7 @@ def load_module_prototypes(*mod_or_prototypes, override=True):
for prototype_key, prot in prots:
prototype = _cleanup_prototype(prototype_key, prot, mod=mod)
# the key can change since in-proto key is given prio over variable-name-based keys
actual_prototype_key = prototype['prototype_key']
actual_prototype_key = prototype["prototype_key"]
if actual_prototype_key in _MODULE_PROTOTYPES and not override:
# don't override - useful to still let settings replace dynamic inserts
@ -462,23 +472,26 @@ def delete_prototype(prototype_key, caller=None):
stored_prototype = DbPrototype.objects.filter(db_key__iexact=prototype_key)
if not stored_prototype:
raise PermissionError(_("Prototype {prototype_key} was not found.").format(
prototype_key=prototype_key))
raise PermissionError(
_("Prototype {prototype_key} was not found.").format(prototype_key=prototype_key)
)
stored_prototype = stored_prototype[0]
if caller:
if not stored_prototype.access(caller, "edit"):
raise PermissionError(
_("{caller} needs explicit 'edit' permissions to "
"delete prototype {prototype_key}.").format(
caller=caller, prototype_key=prototype_key)
_(
"{caller} needs explicit 'edit' permissions to "
"delete prototype {prototype_key}."
).format(caller=caller, prototype_key=prototype_key)
)
stored_prototype.delete()
return True
def search_prototype(key=None, tags=None, require_single=False, return_iterators=False,
no_db=False):
def search_prototype(
key=None, tags=None, require_single=False, return_iterators=False, no_db=False
):
"""
Find prototypes based on key and/or tags, or all prototypes.
@ -520,7 +533,7 @@ def search_prototype(key=None, tags=None, require_single=False, return_iterators
# prototype keys are always in lowecase
if key:
key = key.lower()
key = key.lower()
# search module prototypes
@ -587,10 +600,10 @@ def search_prototype(key=None, tags=None, require_single=False, return_iterators
nmodules = len(module_prototypes)
ndbprots = db_matches.count() if db_matches else 0
if nmodules + ndbprots != 1:
raise KeyError(_(
"Found {num} matching prototypes among {module_prototypes}.").format(
num=nmodules + ndbprots,
module_prototypes=module_prototypes)
raise KeyError(
_("Found {num} matching prototypes among {module_prototypes}.").format(
num=nmodules + ndbprots, module_prototypes=module_prototypes
)
)
if return_iterators:
@ -670,7 +683,7 @@ class PrototypeEvMore(EvMore):
else:
# get the correct slice, adjusted for the db-prototypes
pageno = max(0, pageno - self._npages_db)
return modprot_list[pageno * self.height: pageno * self.height + self.height]
return modprot_list[pageno * self.height : pageno * self.height + self.height]
def page_formatter(self, page):
"""
@ -809,12 +822,15 @@ def validate_prototype(
if is_prototype_base:
_flags["errors"].append(
_("Prototype {protkey} requires `typeclass` " "or 'prototype_parent'.").format(
protkey=protkey)
protkey=protkey
)
)
else:
_flags["warnings"].append(
_("Prototype {protkey} can only be used as a mixin since it lacks "
"'typeclass' or 'prototype_parent' keys.").format(protkey=protkey)
_(
"Prototype {protkey} can only be used as a mixin since it lacks "
"'typeclass' or 'prototype_parent' keys."
).format(protkey=protkey)
)
if strict and typeclass:
@ -822,9 +838,10 @@ def validate_prototype(
class_from_module(typeclass)
except ImportError as err:
_flags["errors"].append(
_("{err}: Prototype {protkey} is based on typeclass {typeclass}, "
"which could not be imported!").format(
err=err, protkey=protkey, typeclass=typeclass)
_(
"{err}: Prototype {protkey} is based on typeclass {typeclass}, "
"which could not be imported!"
).format(err=err, protkey=protkey, typeclass=typeclass)
)
if prototype_parent and isinstance(prototype_parent, dict):
@ -840,20 +857,24 @@ def validate_prototype(
else:
protstring = protstring.lower()
if protkey is not None and protstring == protkey:
_flags["errors"].append(_("Prototype {protkey} tries to parent itself.").format(
protkey=protkey))
_flags["errors"].append(
_("Prototype {protkey} tries to parent itself.").format(protkey=protkey)
)
protparent = protparents.get(protstring)
if not protparent:
_flags["errors"].append(
_("Prototype {protkey}'s `prototype_parent` (named '{parent}') "
"was not found.").format(protkey=protkey, parent=protstring)
_(
"Prototype {protkey}'s `prototype_parent` (named '{parent}') "
"was not found."
).format(protkey=protkey, parent=protstring)
)
# check for infinite recursion
if id(prototype) in _flags["visited"]:
_flags["errors"].append(
_("{protkey} has infinite nesting of prototypes.").format(
protkey=protkey or prototype)
protkey=protkey or prototype
)
)
if _flags["errors"]:
@ -875,9 +896,11 @@ def validate_prototype(
# if we get back to the current level without a typeclass it's an error.
if strict and is_prototype_base and _flags["depth"] <= 0 and not _flags["typeclass"]:
_flags["errors"].append(
_("Prototype {protkey} has no `typeclass` defined anywhere in its parent\n "
"chain. Add `typeclass`, or a `prototype_parent` pointing to a "
"prototype with a typeclass.").format(protkey=protkey)
_(
"Prototype {protkey} has no `typeclass` defined anywhere in its parent\n "
"chain. Add `typeclass`, or a `prototype_parent` pointing to a "
"prototype with a typeclass."
).format(protkey=protkey)
)
if _flags["depth"] <= 0:
@ -901,8 +924,9 @@ def validate_prototype(
prototype["prototype_locks"] = prototype_locks
def protfunc_parser(value, available_functions=None, testing=False, stacktrace=False,
caller=None, **kwargs):
def protfunc_parser(
value, available_functions=None, testing=False, stacktrace=False, caller=None, **kwargs
):
"""
Parse a prototype value string for a protfunc and process it.
@ -1129,8 +1153,9 @@ def value_to_obj(value, force=True):
stype = type(value)
if is_iter(value):
if stype == dict:
return {value_to_obj_or_any(key): value_to_obj_or_any(val)
for key, val in value.items()}
return {
value_to_obj_or_any(key): value_to_obj_or_any(val) for key, val in value.items()
}
else:
return stype([value_to_obj_or_any(val) for val in value])
return dbid_to_obj(value, ObjectDB)

View file

@ -154,8 +154,13 @@ from evennia.prototypes.prototypes import (
_CREATE_OBJECT_KWARGS = ("key", "location", "home", "destination")
_PROTOTYPE_META_NAMES = ("prototype_key", "prototype_desc", "prototype_tags",
"prototype_locks", "prototype_parent")
_PROTOTYPE_META_NAMES = (
"prototype_key",
"prototype_desc",
"prototype_tags",
"prototype_locks",
"prototype_parent",
)
_PROTOTYPE_ROOT_NAMES = (
"typeclass",
"key",
@ -235,9 +240,7 @@ def _get_prototype(inprot, protparents, uninherited=None, _workprot=None):
parent_prototype = protparents.get(prototype.lower(), {})
# Build the prot dictionary in reverse order, overloading
new_prot = _get_prototype(
parent_prototype, protparents, _workprot=_workprot
)
new_prot = _get_prototype(parent_prototype, protparents, _workprot=_workprot)
# attrs, tags have internal structure that should be inherited separately
new_prot["attrs"] = _inherit_attrs(
@ -276,8 +279,9 @@ def flatten_prototype(prototype, validate=False, no_db=False):
if prototype:
prototype = protlib.homogenize_prototype(prototype)
protparents = {prot["prototype_key"].lower(): prot
for prot in protlib.search_prototype(no_db=no_db)}
protparents = {
prot["prototype_key"].lower(): prot for prot in protlib.search_prototype(no_db=no_db)
}
protlib.validate_prototype(
prototype, None, protparents, is_prototype_base=validate, strict=validate
)
@ -342,7 +346,7 @@ def prototype_from_object(obj):
prot["aliases"] = aliases
tags = sorted(
[(tag.db_key, tag.db_category, tag.db_data) for tag in obj.tags.all(return_objs=True)],
key=lambda tup: (str(tup[0]), tup[1] or '', tup[2] or '')
key=lambda tup: (str(tup[0]), tup[1] or "", tup[2] or ""),
)
if tags:
prot["tags"] = tags
@ -351,7 +355,7 @@ def prototype_from_object(obj):
(attr.key, attr.value, attr.category, ";".join(attr.locks.all()))
for attr in obj.attributes.all()
],
key=lambda tup: (str(tup[0]), tup[1] or '', tup[2] or '', tup[3])
key=lambda tup: (str(tup[0]), tup[1] or "", tup[2] or "", tup[3]),
)
if attrs:
prot["attrs"] = attrs
@ -489,8 +493,10 @@ def flatten_diff(diff):
out.extend(_get_all_nested_diff_instructions(val))
else:
raise RuntimeError(
_("Diff contains non-dicts that are not on the "
"form (old, new, action_to_take): {diffpart}").format(diffpart)
_(
"Diff contains non-dicts that are not on the "
"form (old, new, action_to_take): {diffpart}"
).format(diffpart)
)
return out
@ -627,8 +633,9 @@ def format_diff(diff, minimal=True):
return "\n ".join(line for line in texts if line)
def batch_update_objects_with_prototype(prototype, diff=None, objects=None,
exact=False, caller=None):
def batch_update_objects_with_prototype(
prototype, diff=None, objects=None, exact=False, caller=None
):
"""
Update existing objects with the latest version of the prototype.
@ -941,27 +948,32 @@ def spawn(*prototypes, caller=None, **kwargs):
val = prot.pop("location", None)
create_kwargs["db_location"] = init_spawn_value(
val, value_to_obj, caller=caller, prototype=prototype)
val, value_to_obj, caller=caller, prototype=prototype
)
val = prot.pop("home", None)
if val:
create_kwargs["db_home"] = init_spawn_value(val, value_to_obj, caller=caller,
prototype=prototype)
create_kwargs["db_home"] = init_spawn_value(
val, value_to_obj, caller=caller, prototype=prototype
)
else:
try:
create_kwargs["db_home"] = init_spawn_value(
settings.DEFAULT_HOME, value_to_obj, caller=caller, prototype=prototype)
settings.DEFAULT_HOME, value_to_obj, caller=caller, prototype=prototype
)
except ObjectDB.DoesNotExist:
# settings.DEFAULT_HOME not existing is common for unittests
pass
val = prot.pop("destination", None)
create_kwargs["db_destination"] = init_spawn_value(val, value_to_obj, caller=caller,
prototype=prototype)
create_kwargs["db_destination"] = init_spawn_value(
val, value_to_obj, caller=caller, prototype=prototype
)
val = prot.pop("typeclass", settings.BASE_OBJECT_TYPECLASS)
create_kwargs["db_typeclass_path"] = init_spawn_value(val, str, caller=caller,
prototype=prototype)
create_kwargs["db_typeclass_path"] = init_spawn_value(
val, str, caller=caller, prototype=prototype
)
# extract calls to handlers
val = prot.pop("permissions", [])
@ -974,8 +986,13 @@ def spawn(*prototypes, caller=None, **kwargs):
val = prot.pop("tags", [])
tags = []
for (tag, category, *data) in val:
tags.append((init_spawn_value(tag, str, caller=caller, prototype=prototype),
category, data[0] if data else None))
tags.append(
(
init_spawn_value(tag, str, caller=caller, prototype=prototype),
category,
data[0] if data else None,
)
)
prototype_key = prototype.get("prototype_key", None)
if prototype_key:
@ -987,8 +1004,10 @@ def spawn(*prototypes, caller=None, **kwargs):
# extract ndb assignments
nattributes = dict(
(key.split("_", 1)[1], init_spawn_value(val, value_to_obj, caller=caller,
prototype=prototype))
(
key.split("_", 1)[1],
init_spawn_value(val, value_to_obj, caller=caller, prototype=prototype),
)
for key, val in prot.items()
if key.startswith("ndb_")
)
@ -998,8 +1017,13 @@ def spawn(*prototypes, caller=None, **kwargs):
attributes = []
for (attrname, value, *rest) in val:
attributes.append(
(attrname, init_spawn_value(value, caller=caller, prototype=prototype),
rest[0] if rest else None, rest[1] if len(rest) > 1 else None))
(
attrname,
init_spawn_value(value, caller=caller, prototype=prototype),
rest[0] if rest else None,
rest[1] if len(rest) > 1 else None,
)
)
simple_attributes = []
for key, value in (
@ -1010,8 +1034,14 @@ def spawn(*prototypes, caller=None, **kwargs):
continue
else:
simple_attributes.append(
(key, init_spawn_value(value, value_to_obj_or_any, caller=caller,
prototype=prototype), None, None)
(
key,
init_spawn_value(
value, value_to_obj_or_any, caller=caller, prototype=prototype
),
None,
None,
)
)
attributes = attributes + simple_attributes

View file

@ -45,6 +45,7 @@ _PROTPARENTS = {
},
}
class TestSpawner(BaseEvenniaTest):
def setUp(self):
super().setUp()
@ -340,7 +341,6 @@ class TestProtLib(BaseEvenniaTest):
class TestProtFuncs(BaseEvenniaTest):
@override_settings(PROT_FUNC_MODULES=["evennia.prototypes.protfuncs"])
def test_protkey_protfunc(self):
test_prot = {"key1": "value1", "key2": 2}
@ -350,8 +350,7 @@ class TestProtFuncs(BaseEvenniaTest):
"value1",
)
self.assertEqual(
protlib.protfunc_parser("$protkey(key2)", testing=True, prototype=test_prot),
2
protlib.protfunc_parser("$protkey(key2)", testing=True, prototype=test_prot), 2
)
@ -908,6 +907,7 @@ class Test2474(BaseEvenniaTest):
that of its prototype_parent.
"""
prototypes = {
"WEAPON": {
"typeclass": "evennia.objects.objects.DefaultObject",
@ -951,14 +951,14 @@ class TestPartialTagAttributes(BaseEvenniaTest):
def setUp(self):
super().setUp()
self.prot = {
'prototype_key': 'rock',
'typeclass': 'evennia.objects.objects.DefaultObject',
'key': 'a rock',
'tags': [('quantity', 'groupable')], # missing data field
'attrs': [('quantity', 1)], # missing category and lock fields
'desc': 'A good way to get stoned.'
"prototype_key": "rock",
"typeclass": "evennia.objects.objects.DefaultObject",
"key": "a rock",
"tags": [("quantity", "groupable")], # missing data field
"attrs": [("quantity", 1)], # missing category and lock fields
"desc": "A good way to get stoned.",
}
def test_partial_spawn(self):
obj = spawner.spawn(self.prot)
self.assertEqual(obj[0].key, self.prot['key'])
self.assertEqual(obj[0].key, self.prot["key"])