From 67cc36e86eafc46cd8a9682bf5f3a946ef67e58a Mon Sep 17 00:00:00 2001 From: Griatch Date: Sun, 28 Jun 2020 11:09:59 +0200 Subject: [PATCH] Update list_to_string to handle generators. Resolve #2120 --- CHANGELOG.md | 3 +++ evennia/utils/utils.py | 27 +++++++++++++++++---------- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92c3758b52..344c8f0bb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,9 @@ without arguments starts a full interactive Python console. required by Django. - Fixes to `spawn`, make updating an existing prototype/object work better. Add `/raw` switch to `spawn` command to extract the raw prototype dict for manual editing. +- `list_to_string` is now `iter_to_string` (but old name still works as legacy alias). It will + now accept any input, including generators and single values. + ## Evennia 0.9 (2018-2019) diff --git a/evennia/utils/utils.py b/evennia/utils/utils.py index e0a1d8ba8d..cd4d661b8c 100644 --- a/evennia/utils/utils.py +++ b/evennia/utils/utils.py @@ -9,6 +9,7 @@ be of use when designing your own game. import os import gc import sys +import copy import types import math import re @@ -342,14 +343,16 @@ def columnize(string, columns=2, spacing=4, align="l", width=None): return "\n".join(rows) -def list_to_string(inlist, endsep="and", addquote=False): +def iter_to_string(initer, endsep="and", addquote=False): """ - This pretty-formats a list as string output, adding an optional + This pretty-formats an iterable list as string output, adding an optional alternative separator to the second to last entry. If `addquote` is `True`, the outgoing strings will be surrounded by quotes. Args: - inlist (list): The list to print. + initer (any): Usually an iterable to print. Each element must be possible to + present with a string. Note that if this is a generator, it will be + consumed by this operation. endsep (str, optional): If set, the last item separator will be replaced with this value. addquote (bool, optional): This will surround all outgoing @@ -374,16 +377,20 @@ def list_to_string(inlist, endsep="and", addquote=False): endsep = "," else: endsep = " " + endsep - if not inlist: + if not initer: return "" + initer = tuple(str(val) for val in make_iter(initer)) if addquote: - if len(inlist) == 1: - return '"%s"' % inlist[0] - return ", ".join('"%s"' % v for v in inlist[:-1]) + "%s %s" % (endsep, '"%s"' % inlist[-1]) + if len(initer) == 1: + return '"%s"' % initer[0] + return ", ".join('"%s"' % v for v in initer[:-1]) + "%s %s" % (endsep, '"%s"' % initer[-1]) else: - if len(inlist) == 1: - return str(inlist[0]) - return ", ".join(str(v) for v in inlist[:-1]) + "%s %s" % (endsep, inlist[-1]) + if len(initer) == 1: + return str(initer[0]) + return ", ".join(str(v) for v in initer[:-1]) + "%s %s" % (endsep, initer[-1]) + +# legacy alias +list_to_string = iter_to_string def wildcard_to_regexp(instring):