From 5111fb9a1e5f79339f6e35d812a6cb1ef01d8104 Mon Sep 17 00:00:00 2001 From: BlauFeuer Date: Mon, 20 Feb 2017 01:41:43 -0500 Subject: [PATCH] Markup, whitespace, typo and code style fixes --- evennia/utils/utils.py | 63 ++++++++++++++++++++++++------------------ 1 file changed, 36 insertions(+), 27 deletions(-) diff --git a/evennia/utils/utils.py b/evennia/utils/utils.py index 4d1a3b6633..22f5b2d326 100644 --- a/evennia/utils/utils.py +++ b/evennia/utils/utils.py @@ -44,6 +44,7 @@ _DA = object.__delattr__ _DEFAULT_WIDTH = settings.CLIENT_DEFAULT_WIDTH + def is_iter(iterable): """ Checks if an object behaves iterably. @@ -62,6 +63,7 @@ def is_iter(iterable): """ return hasattr(iterable, '__iter__') + def make_iter(obj): """ Makes sure that the object is always iterable. @@ -201,7 +203,7 @@ def justify(text, width=_DEFAULT_WIDTH, align="f", indent=0): distribute odd spaces randomly to one of the gaps. """ line_rest = width - (wlen + ngaps) - gap = " " # minimum gap between words + gap = " " # minimum gap between words if line_rest > 0: if align == 'l': line[-1] += " " * line_rest @@ -211,7 +213,7 @@ def justify(text, width=_DEFAULT_WIDTH, align="f", indent=0): pad = " " * (line_rest // 2) line[0] = pad + line[0] line[-1] = line[-1] + pad + " " * (line_rest % 2) - else: # align 'f' + else: # align 'f' gap += " " * (line_rest // max(1, ngaps)) rest_gap = line_rest % max(1, ngaps) for i in range(rest_gap): @@ -250,8 +252,7 @@ def justify(text, width=_DEFAULT_WIDTH, align="f", indent=0): wlen += word[1] ngaps += 1 - - if line: # catch any line left behind + if line: # catch any line left behind lines.append(_process_line(line)) indentstring = " " * indent return "\n".join([indentstring + line for line in lines]) @@ -360,7 +361,7 @@ def time_format(seconds, style=0): minutes = seconds // 60 seconds -= minutes * 60 - retval = "" + retval = "" if style == 0: """ Standard colon-style output. @@ -522,13 +523,13 @@ def pypath_to_realpath(python_path, file_ending='.py', pypath_prefixes=None): """ path = python_path.strip().split('.') plong = osjoin(*path) + file_ending - pshort = osjoin(*path[1:]) + file_ending if len(path) > 1 else plong # in case we had evennia. or mygame. + pshort = osjoin(*path[1:]) + file_ending if len(path) > 1 else plong # in case we had evennia. or mygame. prefixlong = [osjoin(*ppath.strip().split('.')) - for ppath in make_iter(pypath_prefixes)] \ - if pypath_prefixes else [] + for ppath in make_iter(pypath_prefixes)] \ + if pypath_prefixes else [] prefixshort = [osjoin(*ppath.strip().split('.')[1:]) - for ppath in make_iter(pypath_prefixes) if len(ppath.strip().split('.')) > 1] \ - if pypath_prefixes else [] + for ppath in make_iter(pypath_prefixes) if len(ppath.strip().split('.')) > 1]\ + if pypath_prefixes else [] paths = [plong] + \ [osjoin(_EVENNIA_DIR, prefix, plong) for prefix in prefixlong] + \ [osjoin(_GAME_DIR, prefix, plong) for prefix in prefixlong] + \ @@ -616,6 +617,7 @@ dbid_to_obj = dbref_to_obj _UNICODE_MAP = {"EM DASH": "-", "FIGURE DASH": "-", "EN DASH": "-", "HORIZONTAL BAR": "-", "HORIZONTAL ELLIPSIS": "...", "RIGHT SINGLE QUOTATION MARK": "'"} + def latinify(unicode_string, default='?', pure_ascii=False): """ Convert a unicode string to "safe" ascii/latin-1 characters. @@ -643,7 +645,7 @@ def latinify(unicode_string, default='?', pure_ascii=False): # point name; e.g., since `name(u'á') == 'LATIN SMALL # LETTER A WITH ACUTE'` translate `á` to `a`. However, in # some cases the unicode name is still "LATIN LETTER" - # although no direct equivalent in the Latin alphabeth + # although no direct equivalent in the Latin alphabet # exists (e.g., Þ, "LATIN CAPITAL LETTER THORN") -- we can # avoid these cases by checking that the letter name is # composed of one letter only. @@ -910,6 +912,8 @@ def delay(timedelay, callback, *args, **kwargs): _TYPECLASSMODELS = None _OBJECTMODELS = None + + def clean_object_caches(obj): """ Clean all object caches on the given object. @@ -1146,8 +1150,6 @@ def all_from_module(module): # module if available (try to avoid not imports) members = getmembers(mod, predicate=lambda obj: getmodule(obj) in (mod, None)) return dict((key, val) for key, val in members if not key.startswith("_")) - #return dict((key, val) for key, val in mod.__dict__.items() - # if not (key.startswith("_") or ismodule(val))) def callables_from_module(module): @@ -1209,7 +1211,7 @@ def variable_from_module(module, variable=None, default=None): else: # get all result = [val for key, val in mod.__dict__.items() - if not (key.startswith("_") or ismodule(val))] + if not (key.startswith("_") or ismodule(val))] if len(result) == 1: return result[0] @@ -1348,6 +1350,7 @@ def class_from_module(path, defaultpaths=None): # alias object_from_module = class_from_module + def init_new_player(player): """ Deprecated. @@ -1442,7 +1445,7 @@ def string_partial_matching(alternatives, inp, ret_index=True): # (this will invalidate input in the wrong word order) submatch = [last_index + alt_num for alt_num, alt_word in enumerate(alt_words[last_index:]) - if alt_word.startswith(inp_word)] + if alt_word.startswith(inp_word)] if submatch: last_index = min(submatch) + 1 score += 1 @@ -1488,7 +1491,7 @@ def format_table(table, extra_space=1): for ir, row in enumarate(ftable): if ir == 0: # make first row white - string += "\n{w" + ""join(row) + "{n" + string += "\n|w" + ""join(row) + "|n" else: string += "\n" + "".join(row) print string @@ -1539,6 +1542,8 @@ def get_evennia_pids(): from gc import get_referents from sys import getsizeof + + def deepsize(obj, max_depth=4): """ Get not only size of the given object, but also the size of @@ -1562,21 +1567,22 @@ def deepsize(obj, max_depth=4): """ def _recurse(o, dct, depth): - if max_depth >= 0 and depth > max_depth: + if 0 <= max_depth < depth: return for ref in get_referents(o): idr = id(ref) - if not idr in dct: + if idr not in dct: dct[idr] = (ref, getsizeof(ref, default=0)) _recurse(ref, dct, depth+1) sizedict = {} _recurse(obj, sizedict, 0) - #count = len(sizedict) + 1 size = getsizeof(obj) + sum([p[1] for p in sizedict.values()]) return size # lazy load handler _missing = object() + + class lazy_property(object): """ Delays loading of property until first access. Credit goes to the @@ -1597,14 +1603,14 @@ class lazy_property(object): """ def __init__(self, func, name=None, doc=None): - "Store all properties for now" + """Store all properties for now""" self.__name__ = name or func.__name__ self.__module__ = func.__module__ self.__doc__ = doc or func.__doc__ self.func = func def __get__(self, obj, type=None): - "Triggers initialization" + """Triggers initialization""" if obj is None: return self value = obj.__dict__.get(self.__name__, _missing) @@ -1614,7 +1620,9 @@ class lazy_property(object): return value _STRIP_ANSI = None -_RE_CONTROL_CHAR = re.compile('[%s]' % re.escape(''.join([unichr(c) for c in range(0,32)])))# + range(127,160)]))) +_RE_CONTROL_CHAR = re.compile('[%s]' % re.escape(''.join([unichr(c) for c in range(0, 32)]))) # + range(127,160)]))) + + def strip_control_sequences(string): """ Remove non-print text sequences. @@ -1675,12 +1683,12 @@ def m_len(target): return len(ANSI_PARSER.strip_mxp(target)) return len(target) -#------------------------------------------------------------------ +# ------------------------------------------------------------------- # Search handler function -#------------------------------------------------------------------ +# ------------------------------------------------------------------- # # Replace this hook function by changing settings.SEARCH_AT_RESULT. -# + def at_search_result(matches, caller, query="", quiet=False, **kwargs): """ @@ -1696,7 +1704,7 @@ def at_search_result(matches, caller, query="", quiet=False, **kwargs): should the result pass through. caller (Object): The object performing the search and/or which should receive error messages. - query (str, optional): The search query used to produce `matches`. + query (str, optional): The search query used to produce `matches`. quiet (bool, optional): If `True`, no messages will be echoed to caller on errors. @@ -1774,6 +1782,7 @@ class LimitedSizeOrderedDict(OrderedDict): super(LimitedSizeOrderedDict, self).update(*args, **kwargs) self._check_size() + def get_game_dir_path(): """ This is called by settings_default in order to determine the path @@ -1784,7 +1793,7 @@ def get_game_dir_path(): """ # current working directory, assumed to be somewhere inside gamedir. - for i in range(10): + for _ in range(10): gpath = os.getcwd() if "server" in os.listdir(gpath): if os.path.isfile(os.path.join("server", "conf", "settings.py")):