# evennia.utils.utils

General helper functions that don’t fit neatly under any given category.

They provide some useful string and conversion methods that might be of use when designing your own game.

`evennia.utils.utils.``is_iter`(obj)

  Checks if an object behaves iterably.

  Parameters

    obj (any) – Entity to check for iterability.

  Returns

    is_iterable (bool) – If obj is iterable or not.

  Notes

  Strings are not accepted as iterable (although they are actually iterable), since string iterations are usually not what we want to do with a string.

`evennia.utils.utils.``make_iter`(obj)

  Makes sure that the object is always iterable.

  Parameters

    obj (any) – Object to make iterable.

  Returns

    iterable (list or iterable) –

    The same object

      passed-through or made iterable.

`evennia.utils.utils.``wrap`(text, width=None, indent=0)

  Safely wrap text to a certain number of characters.

  Parameters

    - text (str) – The text to wrap.

    - width (int, optional) – The number of characters to wrap to.

    - indent (int) – How much to indent each line (with whitespace).

  Returns

    text (str) – Properly wrapped text.

`evennia.utils.utils.``fill`(text, width=None, indent=0)

  Safely wrap text to a certain number of characters.

  Parameters

    - text (str) – The text to wrap.

    - width (int, optional) – The number of characters to wrap to.

    - indent (int) – How much to indent each line (with whitespace).

  Returns

    text (str) – Properly wrapped text.

`evennia.utils.utils.``pad`(text, width=None, align='c', fillchar=' ')

  Pads to a given width.

  Parameters

    - text (str) – Text to pad.

    - width (int, optional) – The width to pad to, in characters.

    - align (str, optional) – This is one of ‘c’, ‘l’ or ‘r’ (center, left or right).

    - fillchar (str, optional) – The character to fill with.

  Returns

    text (str) – The padded text.

`evennia.utils.utils.``crop`(text, width=None, suffix='[...]')

  Crop text to a certain width, throwing away text from too-long lines.

  Parameters

    - text (str) – Text to crop.

    - width (int, optional) – Width of line to crop, in characters.

    - suffix (str, optional) – This is appended to the end of cropped lines to show that the line actually continues. Cropping will be done so that the suffix will also fit within the given width. If width is too small to fit both crop and suffix, the suffix will be dropped.

  Returns

    text (str) – The cropped text.

`evennia.utils.utils.``dedent`(text, baseline_index=None, indent=None)

  Safely clean all whitespace at the left of a paragraph.

  Parameters

    - text (str) – The text to dedent.

    - baseline_index (int, optional) – Which row to use as a ‘base’ for the indentation. Lines will be dedented to this level but no further. If None, indent so as to completely deindent the least indented text.

    - indent (int, optional) – If given, force all lines to this indent. This bypasses baseline_index.

  Returns

    text (str) – Dedented string.

  Notes

  This is useful for preserving triple-quoted string indentation while still shifting it all to be next to the left edge of the display.

`evennia.utils.utils.``justify`(text, width=None, align='f', indent=0)

  Fully justify a text so that it fits inside width. When using full justification (default) this will be done by padding between words with extra whitespace where necessary. Paragraphs will be retained.

  Parameters

    - text (str) – Text to justify.

    - width (int, optional) – The length of each line, in characters.

    - align (str, optional) – The alignment, ‘l’, ‘c’, ‘r’ or ‘f’ for left, center, right or full justification respectively.

    - indent (int, optional) – Number of characters indentation of entire justified text block.

  Returns

    justified (str) – The justified and indented block of text.

`evennia.utils.utils.``columnize`(string, columns=2, spacing=4, align='l', width=None)

  Break a string into a number of columns, using as little vertical space as possible.

  Parameters

    - string (str) – The string to columnize.

    - columns (int, optional) – The number of columns to use.

    - spacing (int, optional) – How much space to have between columns.

    - width (int, optional) – The max width of the columns. Defaults to client’s default width.

  Returns

    columns (str) – Text divided into columns.

  Raises

    RuntimeError – If given invalid values.

`evennia.utils.utils.``iter_to_str`(iterable, sep=',', endsep=', and', addquote=False)

  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.

  Parameters

    - iterable (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.

    - sep (str, optional) – The string to use as a separator for each item in the iterable.

    - endsep (str, optional) – The last item separator will be replaced with this value.

    - addquote (bool, optional) – This will surround all outgoing values with double quotes.

  Returns

    str – The list represented as a string.

  Notes

  Default is to use ‘Oxford comma’, like 1, 2, 3, and 4.

  Examples

      >>> iter_to_string([1,2,3], endsep=',')
      '1, 2, 3'
      >>> iter_to_string([1,2,3], endsep='')
      '1, 2 3'
      >>> iter_to_string([1,2,3], ensdep='and')
      '1, 2 and 3'
      >>> iter_to_string([1,2,3], sep=';', endsep=';')
      '1; 2; 3'
      >>> iter_to_string([1,2,3], addquote=True)
      '"1", "2", and "3"'

`evennia.utils.utils.``list_to_string`(iterable, sep=',', endsep=', and', addquote=False)

  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.

  Parameters

    - iterable (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.

    - sep (str, optional) – The string to use as a separator for each item in the iterable.

    - endsep (str, optional) – The last item separator will be replaced with this value.

    - addquote (bool, optional) – This will surround all outgoing values with double quotes.

  Returns

    str – The list represented as a string.

  Notes

  Default is to use ‘Oxford comma’, like 1, 2, 3, and 4.

  Examples

      >>> iter_to_string([1,2,3], endsep=',')
      '1, 2, 3'
      >>> iter_to_string([1,2,3], endsep='')
      '1, 2 3'
      >>> iter_to_string([1,2,3], ensdep='and')
      '1, 2 and 3'
      >>> iter_to_string([1,2,3], sep=';', endsep=';')
      '1; 2; 3'
      >>> iter_to_string([1,2,3], addquote=True)
      '"1", "2", and "3"'

`evennia.utils.utils.``iter_to_string`(iterable, sep=',', endsep=', and', addquote=False)

  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.

  Parameters

    - iterable (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.

    - sep (str, optional) – The string to use as a separator for each item in the iterable.

    - endsep (str, optional) – The last item separator will be replaced with this value.

    - addquote (bool, optional) – This will surround all outgoing values with double quotes.

  Returns

    str – The list represented as a string.

  Notes

  Default is to use ‘Oxford comma’, like 1, 2, 3, and 4.

  Examples

      >>> iter_to_string([1,2,3], endsep=',')
      '1, 2, 3'
      >>> iter_to_string([1,2,3], endsep='')
      '1, 2 3'
      >>> iter_to_string([1,2,3], ensdep='and')
      '1, 2 and 3'
      >>> iter_to_string([1,2,3], sep=';', endsep=';')
      '1; 2; 3'
      >>> iter_to_string([1,2,3], addquote=True)
      '"1", "2", and "3"'

`evennia.utils.utils.``wildcard_to_regexp`(instring)

  Converts a player-supplied string that may have wildcards in it to regular expressions. This is useful for name matching.

  Parameters

    instring (string) – A string that may potentially contain wildcards (* or ?).

  Returns

    regex (str) –

    A string where wildcards were replaced with

      regular expressions.

`evennia.utils.utils.``time_format`(seconds, style=0)

  Function to return a ‘prettified’ version of a value in seconds.

  Parameters

    - seconds (int) – Number if seconds to format.

    - style (int) – One of the following styles: 0. “1d 08:30” 1. “1d” 2. “1 day, 8 hours, 30 minutes” 3. “1 day, 8 hours, 30 minutes, 10 seconds” 4. highest unit (like “3 years” or “8 months” or “1 second”)

  Returns

    timeformatted (str) – A pretty time string.

`evennia.utils.utils.``datetime_format`(dtobj)

  Pretty-prints the time since a given time.

  Parameters

    dtobj (datetime) – An datetime object, e.g. from Django’s DateTimeField.

  Returns

    deltatime (str) –

    A string describing how long ago dtobj

      took place.

`evennia.utils.utils.``host_os_is`(osname)

  Check to see if the host OS matches the query.

  Parameters

    - osname (str) – Common names are “posix” (linux/unix/mac) and “nt” (windows).

    - is_os (bool) – If the os matches or not.

`evennia.utils.utils.``get_evennia_version`(mode='long')

  Helper method for getting the current evennia version.

  Parameters

    mode (str, optional) – One of: - long: 0.9.0 rev342453534 - short: 0.9.0 - pretty: Evennia 0.9.0

  Returns

    version (str) – The version string.

`evennia.utils.utils.``pypath_to_realpath`(python_path, file_ending='.py', pypath_prefixes=None)

  Converts a dotted Python path to an absolute path under the Evennia library directory or under the current game directory.

  Parameters

    - python_path (str) – A dot-python path

    - file_ending (str) – A file ending, including the period.

    - pypath_prefixes (list) – A list of paths to test for existence. These should be on python.path form. EVENNIA_DIR and GAME_DIR are automatically checked, they need not be added to this list.

  Returns

    abspaths (list) –

    All existing, absolute paths created by

      converting python_path to an absolute paths and/or prepending python_path by settings.EVENNIA_DIR, settings.GAME_DIR and by**pypath_prefixes** respectively.

  Notes

  This will also try a few combinations of paths to allow cases where pypath is given including the “evennia.” or “mygame.” prefixes.

`evennia.utils.utils.``dbref`(inp, reqhash=True)

  Converts/checks if input is a valid dbref.

  Parameters

    - inp (int, str) – A database ref on the form N or #N.

    - reqhash (bool, optional) – Require the #N form to accept input as a valid dbref.

  Returns

    dbref (int or None) –

    The integer part of the dbref or None

      if input was not a valid dbref.

`evennia.utils.utils.``dbref_to_obj`(inp, objclass, raise_errors=True)

  Convert a #dbref to a valid object.

  Parameters

    - inp (str or int) – A valid #dbref.

    - objclass (class) – A valid django model to filter against.

    - raise_errors (bool, optional) – Whether to raise errors or return None on errors.

  Returns

    obj (Object or None) – An entity loaded from the dbref.

  Raises

    Exception – If raise_errors is True and objclass.objects.get(id=dbref) did not return a valid object.

`evennia.utils.utils.``dbid_to_obj`(inp, objclass, raise_errors=True)

  Convert a #dbref to a valid object.

  Parameters

    - inp (str or int) – A valid #dbref.

    - objclass (class) – A valid django model to filter against.

    - raise_errors (bool, optional) – Whether to raise errors or return None on errors.

  Returns

    obj (Object or None) – An entity loaded from the dbref.

  Raises

    Exception – If raise_errors is True and objclass.objects.get(id=dbref) did not return a valid object.

`evennia.utils.utils.``latinify`(string, default='?', pure_ascii=False)

  Convert a unicode string to “safe” ascii/latin-1 characters. This is used as a last resort when normal encoding does not work.

  Parameters

    - string (str) – A string to convert to ‘safe characters’ convertible to an latin-1 bytestring later.

    - default (str, optional) – Characters resisting mapping will be replaced with this character or string. The intent is to apply an encode operation on the string soon after.

  Returns

    string (str) –

    A ‘latinified’ string where each unicode character has been

      replaced with a ‘safe’ equivalent available in the ascii/latin-1 charset.

  Notes

  This is inspired by the gist by Ricardo Murri:

    https://gist.github.com/riccardomurri/3c3ccec30f037be174d3

`evennia.utils.utils.``to_bytes`(text, session=None)

  Try to encode the given text to bytes, using encodings from settings or from Session. Will always return a bytes, even if given something that is not str or bytes.

  Parameters

    - text (any) – The text to encode to bytes. If bytes, return unchanged. If not a str, convert to str before converting.

    - session (Session, optional) – A Session to get encoding info from. Will try this before falling back to settings.ENCODINGS.

  Returns

    encoded_text (bytes) –

    the encoded text following the session’s protocol flag followed by the

      encodings specified in settings.ENCODINGS. If all attempt fail, log the error and send the text with “?” in place of problematic characters. If the specified encoding cannot be found, the protocol flag is reset to utf-8. In any case, returns bytes.

  Notes

  If text is already bytes, return it as is.

`evennia.utils.utils.``to_str`(text, session=None)

  Try to decode a bytestream to a python str, using encoding schemas from settings or from Session. Will always return a str(), also if not given a str/bytes.

  Parameters

    - text (any) – The text to encode to bytes. If a str, return it. If also not bytes, convert to str using str() or repr() as a fallback.

    - session (Session, optional) – A Session to get encoding info from. Will try this before falling back to settings.ENCODINGS.

  Returns

    decoded_text (str) – The decoded text.

  Notes

  If text is already str, return it as is.

`evennia.utils.utils.``validate_email_address`(emailaddress)

  Checks if an email address is syntactically correct. Makes use of the django email-validator for consistency.

  Parameters

    emailaddress (str) – Email address to validate.

  Returns

    bool – If this is a valid email or not.

`evennia.utils.utils.``inherits_from`(obj, parent)

  Takes an object and tries to determine if it inherits at any distance from parent.

  Parameters

    - obj (any) – Object to analyze. This may be either an instance or a class.

    - parent (any) – Can be either an instance, a class or the python path to the class.

  Returns

    inherits_from (bool) – If parent is a parent to obj or not.

  Notes

  What differentiates this function from Python’s isinstance() is the flexibility in the types allowed for the object and parent being compared.

`evennia.utils.utils.``server_services`()

  Lists all services active on the Server. Observe that since services are launched in memory, this function will only return any results if called from inside the game.

  Returns

    services (dict) – A dict of available services.

`evennia.utils.utils.``uses_database`(name='sqlite3')

  Checks if the game is currently using a given database. This is a shortcut to having to use the full backend name.

  Parameters

    name (str) – One of ‘sqlite3’, ‘mysql’, ‘postgresql’ or ‘oracle’.

  Returns

    uses (bool) – If the given database is used or not.

`evennia.utils.utils.``delay`(timedelay, callback, *args, **kwargs)

  Delay the calling of a callback (function).

  Parameters

    - timedelay (int or float) – The delay in seconds.

    - callback (callable) – Will be called as callback(*args, **kwargs) after timedelay seconds.

    - *args – Will be used as arguments to callback

  Keyword Arguments

    - persistent (bool, optional) – If True the delay remains after a server restart. persistent is False by default.

    - any (any) – Will be used as keyword arguments to callback.

  Returns

    task (TaskHandlerTask) –

    An instance of a task.

      Refer to, evennia.scripts.taskhandler.TaskHandlerTask

  Notes

  The task handler (evennia.scripts.taskhandler.TASK_HANDLER) will be called for persistent or non-persistent tasks. If persistent is set to True, the callback, its arguments and other keyword arguments will be saved (serialized) in the database, assuming they can be. The callback will be executed even after a server restart/reload, taking into account the specified delay (and server down time). Keep in mind that persistent tasks arguments and callback should not use memory references. If persistent is set to True the delay function will return an int which is the task’s id intended for use with TASK_HANDLER’s do_task and remove methods. All persistent tasks whose time delays have passed will be called on server startup.

`evennia.utils.utils.``repeat`(interval, callback, persistent=True, idstring='', stop=False, store_key=None, *args, **kwargs)

  Start a repeating task using the TickerHandler.

  Parameters

    - interval (int) – How often to call callback.

    - callback (callable) – This will be called with *args, **kwargs every interval seconds. This must be possible to pickle regardless of if persistent is set or not!

    - persistent (bool, optional) – If ticker survives a server reload.

    - idstring (str, optional) – Separates multiple tickers. This is useful mainly if wanting to set up multiple repeats for the same interval/callback but with different args/kwargs.

    - stop (bool, optional) – If set, use the given parameters to _stop_ a running ticker instead of creating a new one.

    - store_key (tuple, optional) – This is only used in combination with stop and should be the return given from the original repeat call. If this is given, all other args except stop are ignored.

    - *args – Used as arguments to callback.

    - **kwargs – Keyword-arguments to pass to callback.

  Returns

    tuple or None – The tuple is the store_key - the identifier for the created ticker. Store this and pass into unrepat() in order to to stop this ticker later. Returns None if stop=True.

  Raises

    KeyError – If trying to stop a ticker that was not found.

`evennia.utils.utils.``unrepeat`(store_key)

  This is used to stop a ticker previously started with repeat.

  Parameters

    store_key (tuple) – This is the return from repeat, used to uniquely identify the ticker to stop. Without the store_key, the ticker must be stopped by passing its parameters to TICKER_HANDLER.remove directly.

  Returns

    bool –

    True if a ticker was stopped, False if not (for example because no

      matching ticker was found or it was already stopped).

`evennia.utils.utils.``run_async`(to_execute, *args, **kwargs)

  Runs a function or executes a code snippet asynchronously.

  Parameters

    to_execute (callable) – If this is a callable, it will be executed with *args and non-reserved **kwargs as arguments. The callable will be executed using ProcPool, or in a thread if ProcPool is not available.

  Keyword Arguments

    - at_return (callable) – Should point to a callable with one argument. It will be called with the return value from to_execute.

    - at_return_kwargs (dict) – This dictionary will be used as keyword arguments to the at_return callback.

    - at_err (callable) – This will be called with a Failure instance if there is an error in to_execute.

    - at_err_kwargs (dict) – This dictionary will be used as keyword arguments to the at_err errback.

  Notes

  All other *args and **kwargs will be passed on to to_execute. Run_async will relay executed code to a thread or procpool.

  Use this function with restrain and only for features/commands that you know has no influence on the cause-and-effect order of your game (commands given after the async function might be executed before it has finished). Accessing the same property from different threads can lead to unpredicted behaviour if you are not careful (this is called a “race condition”).

  Also note that some databases, notably sqlite3, don’t support access from multiple threads simultaneously, so if you do heavy database access from your to_execute under sqlite3 you will probably run very slow or even get tracebacks.

`evennia.utils.utils.``check_evennia_dependencies`()

  Checks the versions of Evennia’s dependencies including making some checks for runtime libraries.

  Returns

    result (bool) –

    False if a show-stopping version mismatch is

      found.

`evennia.utils.utils.``has_parent`(basepath, obj)

  Checks if basepath is somewhere in obj’s parent tree.

  Parameters

    - basepath (str) – Python dotpath to compare against obj path.

    - obj (any) – Object whose path is to be checked.

  Returns

    has_parent (bool) – If the check was successful or not.

`evennia.utils.utils.``mod_import_from_path`(path)

  Load a Python module at the specified path.

  Parameters

    path (str) – An absolute path to a Python module to load.

  Returns

    (module or None) – An imported module if the path was a valid Python module. Returns None if the import failed.

`evennia.utils.utils.``mod_import`(module)

  A generic Python module loader.

  Parameters

    module (str, module) – This can be either a Python path (dot-notation like evennia.objects.models), an absolute path (e.g. /home/eve/evennia/evennia/objects/models.py) or an already imported module object (e.g. models)

  Returns

    (module or None) – An imported module. If the input argument was already a module, this is returned as-is, otherwise the path is parsed and imported. Returns None and logs error if import failed.

`evennia.utils.utils.``all_from_module`(module)

  Return all global-level variables defined in a module.

  Parameters

    module (str, module) – This can be either a Python path (dot-notation like evennia.objects.models), an absolute path (e.g. /home/eve/evennia/evennia/objects.models.py) or an already imported module object (e.g. models)

  Returns

    dict –

    A dict of {variablename: variable} for all

      variables in the given module.

  Notes

  Ignores modules and variable names starting with an underscore, as well as variables imported into the module from other modules.

`evennia.utils.utils.``callables_from_module`(module)

  Return all global-level callables defined in a module.

  Parameters

    module (str, module) – A python-path to a module or an actual module object.

  Returns

    callables (dict) – A dict of {name: callable, …} from the module.

  Notes

  Will ignore callables whose names start with underscore “_”.

`evennia.utils.utils.``variable_from_module`(module, variable=None, default=None)

  Retrieve a variable or list of variables from a module. The variable(s) must be defined globally in the module. If no variable is given (or a list entry is None), all global variables are extracted from the module.

  Parameters

    - module (string or module) – Python path, absolute path or a module.

    - variable (string or iterable, optional) – Single variable name or iterable of variable names to extract. If not given, all variables in the module will be returned.

    - default (string, optional) – Default value to use if a variable fails to be extracted. Ignored if variable is not given.

  Returns

    variables (value or list) – A single value or a list of values depending on if variable is given or not. Errors in lists are replaced by the default argument.

`evennia.utils.utils.``string_from_module`(module, variable=None, default=None)

  This is a wrapper for variable_from_module that requires return value to be a string to pass. It’s primarily used by login screen.

  Parameters

    - module (string or module) – Python path, absolute path or a module.

    - variable (string or iterable, optional) – Single variable name or iterable of variable names to extract. If not given, all variables in the module will be returned.

    - default (string, optional) – Default value to use if a variable fails to be extracted. Ignored if variable is not given.

  Returns

    variables (value or list) – A single (string) value or a list of values depending on if variable is given or not. Errors in lists (such as the value not being a string) are replaced by the default argument.

`evennia.utils.utils.``random_string_from_module`(module)

  Returns a random global string from a module.

  Parameters

    module (string or module) – Python path, absolute path or a module.

  Returns

    random (string) – A random stribg variable from module.

`evennia.utils.utils.``fuzzy_import_from_module`(path, variable, default=None, defaultpaths=None)

  Import a variable based on a fuzzy path. First the literal path will be tried, then all given defaultpaths will be prepended to see a match is found.

  Parameters

    - path (str) – Full or partial python path.

    - variable (str) – Name of variable to import from module.

    - default (string, optional) – Default value to use if a variable fails to be extracted. Ignored if variable is not given.

    - defaultpaths (iterable, options) – Python paths to attempt in order if importing directly from path doesn’t work.

  Returns

    value (any) –

    The variable imported from the module, or default, if

      not found.

`evennia.utils.utils.``class_from_module`(path, defaultpaths=None, fallback=None)

  Return a class from a module, given the class’ full python path. This is primarily used to convert db_typeclass_path:s to classes.

  Parameters

    - path (str) – Full Python dot-path to module.

    - defaultpaths (iterable, optional) – If a direct import from path fails, try subsequent imports by prepending those paths to path.

    - fallback (str) – If all other attempts fail, use this path as a fallback. This is intended as a last-resort. In the example of Evennia loading, this would be a path to a default parent class in the evennia repo itself.

  Returns

    class (Class) – An uninstantiated class recovered from path.

  Raises

    ImportError – If all loading failed.

`evennia.utils.utils.``object_from_module`(path, defaultpaths=None, fallback=None)

  Return a class from a module, given the class’ full python path. This is primarily used to convert db_typeclass_path:s to classes.

  Parameters

    - path (str) – Full Python dot-path to module.

    - defaultpaths (iterable, optional) – If a direct import from path fails, try subsequent imports by prepending those paths to path.

    - fallback (str) – If all other attempts fail, use this path as a fallback. This is intended as a last-resort. In the example of Evennia loading, this would be a path to a default parent class in the evennia repo itself.

  Returns

    class (Class) – An uninstantiated class recovered from path.

  Raises

    ImportError – If all loading failed.

`evennia.utils.utils.``init_new_account`(account)

  Deprecated.

`evennia.utils.utils.``string_similarity`(string1, string2)

  This implements a “cosine-similarity” algorithm as described for example in Proceedings of the 22nd International Conference on Computation Linguistics (Coling 2008), pages 593-600, Manchester, August 2008. The measure-vectors used is simply a “bag of words” type histogram (but for letters).

  Parameters

    - string1 (str) – String to compare (may contain any number of words).

    - string2 (str) – Second string to compare (any number of words).

  Returns

    similarity (float) –

    A value 0…1 rating how similar the two

      strings are.

`evennia.utils.utils.``string_suggestions`(string, vocabulary, cutoff=0.6, maxnum=3)

  Given a string and a vocabulary, return a match or a list of suggestions based on string similarity.

  Parameters

    - string (str) – A string to search for.

    - vocabulary (iterable) – A list of available strings.

    - cutoff (int, 0-1) – Limit the similarity matches (the higher the value, the more exact a match is required).

    - maxnum (int) – Maximum number of suggestions to return.

  Returns

    suggestions (list) – Suggestions from vocabulary with a similarity-rating that higher than or equal to cutoff. Could be empty if there are no matches.

`evennia.utils.utils.``string_partial_matching`(alternatives, inp, ret_index=True)

  Partially matches a string based on a list of alternatives. Matching is made from the start of each subword in each alternative. Case is not important. So e.g. “bi sh sw” or just “big” or “shiny” or “sw” will match “Big shiny sword”. Scoring is done to allow to separate by most common denominator. You will get multiple matches returned if appropriate.

  Parameters

    - alternatives (list of str) – A list of possible strings to match.

    - inp (str) – Search criterion.

    - ret_index (bool, optional) – Return list of indices (from alternatives array) instead of strings.

  Returns

    matches (list) – String-matches or indices if ret_index is True.

`evennia.utils.utils.``format_table`(table, extra_space=1)

  Format a 2D array of strings into a multi-column table.

  Parameters

    - table (list) – A list of lists to represent columns in the table: [[val,val,val,…], [val,val,val,…], …], where each val will be placed on a separate row in the column. All columns must have the same number of rows (some positions may be empty though).

    - extra_space (int, optional) – Sets how much minimum extra padding (in characters) should be left between columns.

  Returns

    list – A list of lists representing the rows to print out one by one.

  Notes

  The function formats the columns to be as wide as the widest member of each column.

  evennia.utils.evtable is more powerful than this, but this function can be useful when the number of columns and rows are unknown and must be calculated on the fly.

  Examples:

      ftable = format_table([[1,2,3], [4,5,6]])
      string = ""
      for ir, row in enumerate(ftable):
          if ir == 0:
              # make first row white
              string += "\n|w" + "".join(row) + "|n"
          else:
              string += "\n" + "".join(row)
      print(string)

`evennia.utils.utils.``percent`(value, minval, maxval, formatting='{:3.1f}%')

  Get a value in an interval as a percentage of its position in that interval. This also understands negative numbers.

  Parameters

    - value (number) – This should be a value minval<=value<=maxval.

    - minval (number or None) – Smallest value in interval. This could be None for an open interval (then return will always be 100%)

    - maxval (number or None) – Biggest value in interval. This could be None for an open interval (then return will always be 100%)

    - formatted (str, optional) – This is a string that should accept one formatting tag. This will receive the current value as a percentage. If None, the raw float will be returned instead.

  Returns

    str or float – The formatted value or the raw percentage as a float.

  Notes

  We try to handle a weird interval gracefully.

  - If either maxval or minval is None (open interval), we (aribtrarily) assume 100%.

  - If minval > maxval, we return 0%.

  - If minval == maxval == value we are looking at a single value match and return 100%.

  - If minval == maxval != value we return 0%.

  - If value not in [minval..maxval], we set value to the closest boundary, so the result will be 0% or 100%, respectively.

`evennia.utils.utils.``percentile`(iterable, percent, key=<function <lambda>>)

  Find the percentile of a list of values.

  Parameters

    - iterable (iterable) – A list of values. Note N MUST BE already sorted.

    - percent (float) – A value from 0.0 to 1.0.

    - key (callable, optional) –

  Returns

    float – The percentile of the values

`evennia.utils.utils.``format_grid`(elements, width=78, sep=' ', verbatim_elements=None, line_prefix='')

  This helper function makes a ‘grid’ output, where it distributes the given string-elements as evenly as possible to fill out the given width. will not work well if the variation of length is very big!

  Parameters

    - elements (iterable) – A 1D list of string elements to put in the grid.

    - width (int, optional) – The width of the grid area to fill.

    - sep (str, optional) – The extra separator to put between words. If set to the empty string, words may run into each other.

    - verbatim_elements (list, optional) – This is a list of indices pointing to specific items in the elements list. An element at this index will not be included in the calculation of the slot sizes. It will still be inserted into the grid at the correct position and may be surrounded by padding unless filling the entire line. This is useful for embedding decorations in the grid, such as horizontal bars.

    - ignore_ansi (bool, optional) – Ignore ansi markups when calculating white spacing.

    - line_prefix (str, optional) – A prefix to add at the beginning of each line. This can e.g. be used to preserve line color across line breaks.

  Returns

    list – The grid as a list of ready-formatted rows. We return it like this to make it easier to insert decorations between rows, such as horizontal bars.

`evennia.utils.utils.``get_evennia_pids`()

  Get the currently valid PIDs (Process IDs) of the Portal and Server by trying to access a PID file.

  Returns

    server, portal (tuple) –

    The PIDs of the respective processes,

      or two None values if not found.

  Examples

  This can be used to determine if we are in a subprocess by

      self_pid = os.getpid()
      server_pid, portal_pid = get_evennia_pids()
      is_subprocess = self_pid not in (server_pid, portal_pid)

`evennia.utils.utils.``deepsize`(obj, max_depth=4)

  Get not only size of the given object, but also the size of objects referenced by the object, down to max_depth distance from the object.

  Parameters

    - obj (object) – the object to be measured.

    - max_depth (int, optional) – maximum referential distance from obj that deepsize() should cover for measuring objects referenced by obj.

  Returns

    size (int) – deepsize of obj in Bytes.

  Notes

  This measure is necessarily approximate since some memory is shared between objects. The max_depth of 4 is roughly tested to give reasonable size information about database models and their handlers.

class `evennia.utils.utils.``lazy_property`(func, name=None, doc=None)

  Bases: `object`

  Delays loading of property until first access. Credit goes to the Implementation in the werkzeug suite: http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property

  This should be used as a decorator in a class and in Evennia is mainly used to lazy-load handlers:

  >     @lazy_property
  >     def attributes(self):
  >         return AttributeHandler(self)

  Once initialized, the AttributeHandler will be available as a property “attributes” on the object. This is read-only since this functionality is pretty much exclusively used by handlers.

  `__init__`(func, name=None, doc=None)

    Store all properties for now

`evennia.utils.utils.``strip_control_sequences`(string)

  Remove non-print text sequences.

  Parameters

    string (str) – Text to strip.

  Returns.

    text (str): Stripped text.

`evennia.utils.utils.``calledby`(callerdepth=1)

  Only to be used for debug purposes. Insert this debug function in another function; it will print which function called it.

  Parameters

    callerdepth (int) – Must be larger than 0. When > 1, it will print the caller of the caller etc.

  Returns

    calledby (str) –

    A debug string detailing which routine called

      us.

`evennia.utils.utils.``m_len`(target)

  Provides length checking for strings with MXP patterns, and falls back to normal len for other objects.

  Parameters

    target (str) – A string with potential MXP components to search.

  Returns

    length (int) – The length of target, ignoring MXP components.

`evennia.utils.utils.``display_len`(target)

  Calculate the ‘visible width’ of text. This is not necessarily the same as the number of characters in the case of certain asian characters. This will also strip MXP patterns.

  Parameters

    target (any) – Something to measure the length of. If a string, it will be measured keeping asian-character and MXP links in mind.

  Returns

    int – The visible width of the target.

`evennia.utils.utils.``at_search_result`(matches, caller, query='', quiet=False, **kwargs)

  This is a generic hook for handling all processing of a search result, including error reporting. This is also called by the cmdhandler to manage errors in command lookup.

  Parameters

    - matches (list) – This is a list of 0, 1 or more typeclass instances or Command instances, the matched result of the search. If 0, a nomatch error should be echoed, and if >1, multimatch errors should be given. Only if a single match should the result pass through.

    - caller (Object) – The object performing the search and/or which should

    - error messages. (receive) –

    - query (str, optional) – The search query used to produce matches.

    - quiet (bool, optional) – If True, no messages will be echoed to caller on errors.

  Keyword Arguments

    - nofound_string (str) – Replacement string to echo on a notfound error.

    - multimatch_string (str) – Replacement string to echo on a multimatch error.

  Returns

    processed_result (Object or None) – This is always a single result or None. If None, any error reporting/handling should already have happened. The returned object is of the type we are checking multimatches for (e.g. Objects or Commands)

class `evennia.utils.utils.``LimitedSizeOrderedDict`(*args, **kwargs)

  Bases: `collections.OrderedDict`

  This dictionary subclass is both ordered and limited to a maximum number of elements. Its main use is to hold a cache that can never grow out of bounds.

  `__init__`(*args, **kwargs)

    Limited-size ordered dict.

    Keyword Arguments

      - size_limit (int) – Use this to limit the number of elements alloweds to be in this list. By default the overshooting elements will be removed in FIFO order.

      - fifo (bool, optional) – Defaults to True. Remove overshooting elements in FIFO order. If False, remove in FILO order.

  `update`([E, ]**F) → None. Update D from dict/iterable E and F.

    If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

`evennia.utils.utils.``get_game_dir_path`()

  This is called by settings_default in order to determine the path of the game directory.

  Returns

    path (str) – Full OS path to the game dir

`evennia.utils.utils.``get_all_typeclasses`(parent=None)

  List available typeclasses from all available modules.

  Parameters

    parent (str, optional) – If given, only return typeclasses inheriting (at any distance) from this parent.

  Returns

    dict – On the form {“typeclass.path”: typeclass, …}

  Notes

  This will dynamically retrieve all abstract django models inheriting at any distance from the TypedObject base (aka a Typeclass) so it will work fine with any custom classes being added.

`evennia.utils.utils.``get_all_cmdsets`(parent=None)

  List available cmdsets from all available modules.

  Parameters

    parent (str, optional) – If given, only return cmdsets inheriting (at any distance) from this parent.

  Returns

    dict – On the form {“cmdset.path”: cmdset, …}

  Notes

  This will dynamically retrieve all abstract django models inheriting at any distance from the CmdSet base so it will work fine with any custom classes being added.

`evennia.utils.utils.``interactive`(func)

  Decorator to make a method pausable with yield(seconds) and able to ask for user-input with response=yield(question). For the question-asking to work, one of the args or kwargs to the decorated function must be named ‘caller’.

  Raises

    - ValueError – If asking an interactive question but the decorated function has no arg or kwarg named ‘caller’.

    - ValueError – If passing non int/float to yield using for pausing.

  Examples

      @interactive
      def myfunc(caller):
          caller.msg("This is a test")
          # wait five seconds
          yield(5)
          # ask user (caller) a question
          response = yield("Do you want to continue waiting?")
          if response == "yes":
              yield(5)
          else:
              # ...

  Notes

  This turns the decorated function or method into a generator.

`evennia.utils.utils.``safe_convert_to_types`(converters, *args, raise_errors=True, **kwargs)

  Helper function to safely convert inputs to expected data types.

  Parameters

    - converters (tuple) – A tuple ((converter, converter,…), {kwarg: converter, …}) to match a converter to each element in *args and **kwargs. Each converter will will be called with the arg/kwarg-value as the only argument. If there are too few converters given, the others will simply not be converter. If the converter is given as the string ‘py’, it attempts to run safe_eval/literal_eval on the input arg or kwarg value. It’s possible to skip the arg/kwarg part of the tuple, an empty tuple/dict will then be assumed.

    - *args – The arguments to convert with argtypes.

    - raise_errors (bool, optional) – If set, raise any errors. This will abort the conversion at that arg/kwarg. Otherwise, just skip the conversion of the failing arg/kwarg. This will be set by the FuncParser if this is used as a part of a FuncParser callable.

    - **kwargs – The kwargs to convert with kwargtypes

  Returns

    tuple – (args, kwargs) in converted form.

  Raises

    - utils.funcparser.ParsingError – If parsing failed in the ‘py’ converter. This also makes this compatible with the FuncParser interface.

    - any – Any other exception raised from other converters, if raise_errors is True.

  Notes

  This function is often used to validate/convert input from untrusted sources. For security, the “py”-converter is deliberately limited and uses safe_eval/literal_eval which only supports simple expressions or simple containers with literals. NEVER use the python eval or exec methods as a converter for any untrusted input! Allowing untrusted sources to execute arbitrary python on your server is a severe security risk,

  Example:

      $funcname(1, 2, 3.0, c=[1,2,3])

      def _funcname(*args, **kwargs):
          args, kwargs = safe_convert_input(((int, int, float), {'c': 'py'}), *args, **kwargs)
          # ...

`evennia.utils.utils.``strip_unsafe_input`(txt, session=None, bypass_perms=None)

  Remove ‘unsafe’ text codes from text; these are used to elimitate exploits in user-provided data, such as html-tags, line breaks etc.

  Parameters

    - txt (str) – The text to clean.

    - session (Session, optional) – A Session in order to determine if the check should be bypassed by permission (will be checked with the ‘perm’ lock, taking permission hierarchies into account).

    - bypass_perms (list, optional) – Iterable of permission strings to check for bypassing the strip. If not given, use settings.INPUT_CLEANUP_BYPASS_PERMISSIONS.

  Returns

    str – The cleaned string.

  Notes

  The INPUT_CLEANUP_BYPASS_PERMISSIONS list defines what account permissions are required to bypass this strip.

`evennia.utils.utils.``copy_word_case`(base_word, new_word)

  Converts a word to use the same capitalization as a first word.

  Parameters

    - base_word (str) – A word to get the capitalization from.

    - new_word (str) – A new word to capitalize in the same way as base_word.

  Returns

    str – The new_word with capitalization matching the first word.

  Notes

  This is meant for words. Longer sentences may get unexpected results.

  If the two words have a mix of capital/lower letters _and_ new_word is longer than base_word, the excess will retain its original case.

`evennia.utils.utils.``run_in_main_thread`(function_or_method, *args, **kwargs)

  Force a callable to execute in the main Evennia thread. This is only relevant when calling code from e.g. web views, which run in a separate threadpool. Use this to avoid race conditions.

  Parameters

    - function_or_method (callable) – A function or method to fire.

    - *args – Will be passed into the callable.

    - **kwargs – Will be passed into the callable.

`evennia.utils.utils.``int2str`(number, adjective=False)

  Convert a number to an English string for better display; so 1 -> one, 2 -> two etc up until 12, after which it will be ‘13’, ‘14’ etc.

  Parameters

    - number (int) – The number to convert. Floats will be converted to ints.

    - adjective (int) – If set, map 1->1st, 2->2nd etc. If unset, map 1->one, 2->two etc. up to twelve.

  Returns

    str – The number expressed as a string.