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)[source]¶ 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)[source]¶ 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)[source]¶ 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=' ')[source]¶ 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='[...]')[source]¶ 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)[source]¶ Safely clean all whitespace at the left of a paragraph.
- Parameters
text (str) – The text to dedent.
baseline_index (int or None, 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.
- 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)[source]¶ 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)[source]¶ 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_string
(initer, endsep='and', addquote=False)[source]¶ 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
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 values with double quotes.
- Returns
liststr (str) – The list represented as a string.
Examples
# no endsep: [1,2,3] -> '1, 2, 3' # with endsep=='and': [1,2,3] -> '1, 2 and 3' # with addquote and endsep [1,2,3] -> '"1", "2" and "3"'
-
evennia.utils.utils.
list_to_string
(initer, 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
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 values with double quotes.
- Returns
liststr (str) – The list represented as a string.
Examples
# no endsep: [1,2,3] -> '1, 2, 3' # with endsep=='and': [1,2,3] -> '1, 2 and 3' # with addquote and endsep [1,2,3] -> '"1", "2" and "3"'
-
evennia.utils.utils.
wildcard_to_regexp
(instring)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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')[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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:
-
evennia.utils.utils.
to_bytes
(text, session=None)[source]¶ 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.
Note
If text is already bytes, return it as is.
-
evennia.utils.utils.
to_str
(text, session=None)[source]¶ 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.
Note
If text is already str, return it as is.
-
evennia.utils.utils.
validate_email_address
(emailaddress)[source]¶ 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)[source]¶ 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 instance, class or python path to class.
- Returns
inherits_from (bool) – If parent is a parent to obj or not.
Notes
What differs this function from e.g. isinstance() is that obj may be both an instance and a class, and parent may be an instance, a class, or the python path to a class (counting from the evennia root directory).
-
evennia.utils.utils.
server_services
()[source]¶ 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')[source]¶ 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’
'oracle'. (or) –
- Returns
uses (bool) – If the given database is used or not.
-
evennia.utils.utils.
delay
(timedelay, callback, *args, **kwargs)[source]¶ 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 (any) – 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
Note
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.
run_async
(to_execute, *args, **kwargs)[source]¶ 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
()[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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
variables (dict) –
- A dict of {variablename: variable} for all
variables in the given module.
Notes
Ignores modules and variable names starting with an underscore.
-
evennia.utils.utils.
callables_from_module
(module)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ Return a class from a module, given the module’s 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 module’s 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.
string_similarity
(string1, string2)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ Note: 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.
- Args.
- 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
table (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.
Example
ftable = format_table([[...], [...], ...]) 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.
get_evennia_pids
()[source]¶ 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 something like:
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)[source]¶ 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)[source]¶ 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.
-
evennia.utils.utils.
strip_control_sequences
(string)[source]¶ Remove non-print text sequences.
- Parameters
string (str) – Text to strip.
- Returns.
text (str): Stripped text.
-
evennia.utils.utils.
calledby
(callerdepth=1)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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.
-
-
evennia.utils.utils.
get_game_dir_path
()[source]¶ 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)[source]¶ List available typeclasses from all available modules.
- Parameters
parent (str, optional) – If given, only return typeclasses inheriting (at any distance) from this parent.
- Returns
typeclasses (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.
interactive
(func)[source]¶ 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, ‘caller’ must the name of an argument or kwarg to the decorated function.
Example:
@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 method into a generator!