evennia.utils.funcparser

Generic function parser for functions embedded in a string, on the form $funcname(*args, **kwargs), for example:

“A string $foo() with $bar(a, b, c, $moo(), d=23) etc.”

Each arg/kwarg can also be another nested function. These will be executed inside-out and their return will used as arguments for the enclosing function (so the same as for regular Python function execution).

This is the base for all forms of embedded func-parsing, like inlinefuncs and protfuncs. Each function available to use must be registered as a ‘safe’ function for the parser to accept it. This is usually done in a module with regular Python functions on the form:

# in a module whose path is passed to the parser

def _helper(x):
    # use underscore to NOT make the function available as a callable

def funcname(*args, **kwargs):
    # this can be accecssed as $funcname(*args, **kwargs)
    # it must always accept *args and **kwargs.
    ...
    return something

Usage:

from evennia.utils.funcparser

parser = FuncParser("path.to.module_with_callables")
result = parser.parse("String with $funcname() in it")

The FuncParser also accepts a direct dict mapping of {‘name’: callable, …}.

exception evennia.utils.funcparser.ParsingError[source]

Bases: RuntimeError

Failed to parse for some reason.

class evennia.utils.funcparser.FuncParser(callables, start_char='$', escape_char='\\', max_nesting=20, **default_kwargs)[source]

Bases: object

Sets up a parser for strings containing $funcname(*args, **kwargs) substrings.

__init__(callables, start_char='$', escape_char='\\', max_nesting=20, **default_kwargs)[source]

Initialize the parser.

Parameters
  • callables (str, module, list or dict) – Where to find ‘safe’ functions to make available in the parser. If a dict, it should be a direct mapping {“funcname”: callable, …}. If one or mode modules or module-paths, the module(s) are first checked for a dict FUNCPARSER_CALLABLES = {“funcname”, callable, …}. If no such variable exists, all callables in the module (whose name does not start with an underscore) will be made available to the parser.

  • start_char (str, optional) – A character used to identify the beginning of a parseable function. Default is $.

  • escape_char (str, optional) – Prepend characters with this to have them not count as a function. Default is the backtick, \.

  • max_nesting (int, optional) – How many levels of nested function calls are allowed, to avoid exploitation. Default is 20.

  • **default_kwargs – These kwargs will be passed into all callables. These kwargs can be overridden both by kwargs passed direcetly to .parse and by kwargs given directly in the string $funcname call. They are suitable for global defaults that is intended to be changed by the user. To guarantee a call always gets a particular kwarg, pass it into .parse as **reserved_kwargs instead.

validate_callables(callables)[source]

Validate the loaded callables. Each callable must support at least funcname(*args, **kwargs). property.

Parameters

callables (dict) – A mapping {“funcname”: callable, …} to validate

Raises

AssertionError – If invalid callable was found.

Notes

This is also a good method to override for individual parsers needing to run any particular pre-checks.

execute(parsedfunc, raise_errors=False, **reserved_kwargs)[source]

Execute a parsed function

Parameters
  • parsedfunc (_ParsedFunc) – This dataclass holds the parsed details of the function.

  • raise_errors (bool, optional) – Raise errors. Otherwise return the string with the function unparsed.

  • **reserved_kwargs – These kwargs are _guaranteed_ to always be passed into the callable on every call. It will override any default kwargs _and_ also a same-named kwarg given manually in the $funcname call. This is often used by Evennia to pass required data into the callable, for example the current Session for inlinefuncs.

Returns

any

The result of the execution. If this is a nested function, it

can be anything, otherwise it will be converted to a string later. Always a string on un-raised error (the unparsed function string).

Raises
  • ParsingError, any – A ParsingError if the function could not be

  • found, otherwise error from function definition. Only raised if

  • raise_errors

Notes

The kwargs passed into the callable will be a mixture of the default_kwargs passed into FuncParser.__init__, kwargs given directly in the $funcdef string, and the reserved_kwargs this function gets from .parse(). For colliding keys, funcdef-defined kwargs will override default kwargs while reserved kwargs will always override the other two.

parse(string, raise_errors=False, escape=False, strip=False, return_str=True, **reserved_kwargs)[source]

Use parser to parse a string that may or may not have $funcname(*args, **kwargs) - style tokens in it. Only the callables used to initiate the parser will be eligible for parsing.

Parameters
  • string (str) – The string to parse.

  • raise_errors (bool, optional) – By default, a failing parse just means not parsing the string but leaving it as-is. If this is True, errors (like not closing brackets) will lead to an ParsingError.

  • escape (bool, optional) – If set, escape all found functions so they are not executed by later parsing.

  • strip (bool, optional) – If set, strip any inline funcs from string as if they were not there.

  • return_str (bool, optional) – If set (default), always convert the parse result to a string, otherwise return the result of the latest called inlinefunc (if called separately).

  • **reserved_kwargs – If given, these are guaranteed to _always_ pass as part of each parsed callable’s kwargs. These override same-named default options given in **__init__ as well as any same-named kwarg given in the string function. This is because it is often used by Evennia to pass necessary kwargs into each callable (like the current Session object for inlinefuncs).

Returns

str or any

The parsed string, or the same string on error (if

raise_errors is False). This is always a string

Raises

ParsingError – If a problem is encountered and raise_errors is True.

parse_to_any(string, raise_errors=False, **reserved_kwargs)[source]

This parses a string and if the string only contains a “$func(…)”, the return will be the return value of that function, even if it’s not a string. If mixed in with other strings, the result will still always be a string.

Parameters
  • string (str) – The string to parse.

  • raise_errors (bool, optional) – If unset, leave a failing (or unrecognized) inline function as unparsed in the string. If set, raise an ParsingError.

  • **reserved_kwargs – If given, these are guaranteed to _always_ pass as part of each parsed callable’s kwargs. These override same-named default options given in **__init__ as well as any same-named kwarg given in the string function. This is because it is often used by Evennia to pass necessary kwargs into each callable (like the current Session object for inlinefuncs).

Returns

any

The return from the callable. Or string if the callable is not

given alone in the string.

Raises

ParsingError – If a problem is encountered and raise_errors is True.

Notes

This is a convenience wrapper for self.parse(…, return_str=False) which accomplishes the same thing.

Examples

from ast import literal_eval
from evennia.utils.funcparser import FuncParser


def ret1(*args, **kwargs):
    return 1

parser = FuncParser({"lit": lit})

assert parser.parse_to_any("$ret1()" == 1
assert parser.parse_to_any("$ret1() and text" == '1 and text'
evennia.utils.funcparser.funcparser_callable_eval(*args, **kwargs)[source]

Funcparser callable. This will combine safe evaluations to try to parse the incoming string into a python object. If it fails, the return will be same as the input.

Parameters

string (str) – The string to parse. Only simple literals or operators are allowed.

Returns

any – The string parsed into its Python form, or the same as input.

Examples

  • $py(1) -> 1

  • $py([1,2,3,4] -> [1, 2, 3]

  • $py(3 + 4) -> 7

evennia.utils.funcparser.funcparser_callable_toint(*args, **kwargs)[source]

Usage: toint(43.0) -> 43

evennia.utils.funcparser.funcparser_callable_add(*args, **kwargs)[source]

Usage: $add(val1, val2) -> val1 + val2

evennia.utils.funcparser.funcparser_callable_sub(*args, **kwargs)[source]

Usage: **$sub(val1, val2) -> val1 - val2

evennia.utils.funcparser.funcparser_callable_mult(*args, **kwargs)[source]

Usage: $mult(val1, val2) -> val1 * val2

evennia.utils.funcparser.funcparser_callable_div(*args, **kwargs)[source]

Usage: $mult(val1, val2) -> val1 / val2

evennia.utils.funcparser.funcparser_callable_round(*args, **kwargs)[source]

Funcparser callable. Rounds an incoming float to a certain number of significant digits.

Parameters
  • inp (str or number) – If a string, it will attempt to be converted to a number first.

  • significant (int) – The number of significant digits. Default is None - this will turn the result into an int.

Returns

any – The rounded value or inp if inp was not a number.

Examples

  • $round(3.5434343, 3) -> 3.543

  • $round($random(), 2) - rounds random result, e.g 0.22

evennia.utils.funcparser.funcparser_callable_random(*args, **kwargs)[source]

Funcparser callable. Returns a random number between 0 and 1, from 0 to a maximum value, or within a given range (inclusive).

Parameters
  • minval (str, optional) – Minimum value. If not given, assumed 0.

  • maxval (str, optional) – Maximum value.

Notes

If either of the min/maxvalue has a ‘.’ in it, a floating-point random value will be returned. Otherwise it will be an integer value in the given range.

Examples

  • $random() - random value [0 .. 1) (float).

  • $random(5) - random value [0..5] (int)

  • $random(5.0) - random value [0..5] (float)

  • $random(5, 10) - random value [5..10] (int)

  • $random(5, 10.0) - random value [5..10] (float)

evennia.utils.funcparser.funcparser_callable_randint(*args, **kwargs)[source]

Usage: $randint(start, end):

Legacy alias - always returns integers.

evennia.utils.funcparser.funcparser_callable_choice(*args, **kwargs)[source]

FuncParser callable. Picks a random choice from a list.

Parameters

listing (list) – A list of items to randomly choose between. This will be converted from a string to a real list.

Returns

any – The randomly chosen element.

Example

  • $choice([key, flower, house])

  • $choice([1, 2, 3, 4])

evennia.utils.funcparser.funcparser_callable_pad(*args, **kwargs)[source]

FuncParser callable. Pads text to given width, optionally with fill-characters

Parameters
  • text (str) – Text to pad.

  • width (int) – Width of padding.

  • align (str, optional) – Alignment of padding; one of ‘c’, ‘l’ or ‘r’.

  • fillchar (str, optional) – Character used for padding. Defaults to a space.

Example

  • $pad(text, 12, r, ‘ ‘) -> ” text”

  • $pad(text, width=12, align=c, fillchar=-) -> “—-text—-”

evennia.utils.funcparser.funcparser_callable_crop(*args, **kwargs)[source]

FuncParser callable. Crops ingoing text to given widths.

Parameters
  • text (str, optional) – Text to crop.

  • width (str, optional) – Will be converted to an integer. Width of crop in characters.

  • suffix (str, optional) – End string to mark the fact that a part of the string was cropped. Defaults to […].

Example

  • $crop(A long text, 10, […]) -> “A lon[…]”

  • $crop(text, width=11, suffix=’[…]) -> “A long[…]”

evennia.utils.funcparser.funcparser_callable_space(*args, **kwarg)[source]

Usage: $space(43)

Insert a length of space.

evennia.utils.funcparser.funcparser_callable_justify(*args, **kwargs)[source]

Justify text across a width, default across screen width.

Parameters
  • text (str) – Text to justify.

  • width (int, optional) – Defaults to default screen width.

  • align (str, optional) – One of ‘l’, ‘c’, ‘r’ or ‘f’ for ‘full’.

  • indent (int, optional) – Intendation of text block, if any.

Returns

str – The justified text.

Examples

  • $just(text, width=40)

  • $just(text, align=r, indent=2)

evennia.utils.funcparser.funcparser_callable_left_justify(*args, **kwargs)[source]

Usage: $ljust(text)

evennia.utils.funcparser.funcparser_callable_right_justify(*args, **kwargs)[source]

Usage: $rjust(text)

evennia.utils.funcparser.funcparser_callable_center_justify(*args, **kwargs)[source]

Usage: $cjust(text)

evennia.utils.funcparser.funcparser_callable_clr(*args, **kwargs)[source]

FuncParser callable. Colorizes nested text.

Parameters
  • startclr (str, optional) – An ANSI color abbreviation without the prefix |, such as r (red foreground) or [r (red background).

  • text (str, optional) – Text

  • endclr (str, optional) – The color to use at the end of the string. Defaults to |n (reset-color).

Kwargs:

color (str, optional): If given,

Example

  • $clr(r, text, n) -> “|rtext|n”

  • $clr(r, text) -> “|rtext|n

  • $clr(text, start=r, end=n) -> “|rtext|n”

FuncParser callable. Finds an object based on name or #dbref. Note that this requries the parser be called with the caller’s Session for proper security. If called without session, the call is aborted.

Parameters

query (str) – The key or dbref to search for.

Keyword Arguments
  • return_list (bool) – If set, return a list of objects with 0, 1 or more matches to query. Defaults to False.

  • type (str) – One of ‘obj’, ‘account’, ‘script’

  • caller (Entity) – Supplied to Parser. This is required and will be passed into the access check for the entity being searched for. The ‘control’ permission is required.

  • access (str) – Which locktype access to check. Unset to disable the security check.

Returns

any – An entity match or None if no match or a list if return_list is set.

Raises

ParsingError – If zero/multimatch and return_list is False, or caller was not passed into parser.

Examples

  • “$search(#233)”

  • “$search(Tom, type=account)”

  • “$search(meadow, return_list=True)”

evennia.utils.funcparser.funcparser_callable_search_list(*args, caller=None, access='control', **kwargs)[source]

Usage: $objlist(#123)

Legacy alias for search with a return_list=True kwarg preset.

evennia.utils.funcparser.funcparser_callable_you(*args, caller=None, receiver=None, mapping=None, capitalize=False, **kwargs)[source]

Usage: $you() or $you(key)

Replaces with you for the caller of the string, with the display_name of the caller for others.

Keyword Arguments
  • caller (Object) – The ‘you’ in the string. This is used unless another you-key is passed to the callable in combination with mapping.

  • receiver (Object) – The recipient of the string.

  • mapping (dict, optional) – This is a mapping {key:Object, …} and is used to find which object $you(key) refers to. If not given, the caller kwarg is used.

  • capitalize (bool) – Passed by the You helper, to capitalize you.

Returns

str – The parsed string.

Raises

ParsingError – If caller and receiver were not supplied.

Notes

The kwargs should be passed the to parser directly.

Examples

This can be used by the say or emote hooks to pass actor stance strings. This should usually be combined with the $inflect() callable.

  • With a grin, $you() $conj(jump) at $you(tommy).

The caller-object will see “With a grin, you jump at Tommy.” Tommy will see “With a grin, CharName jumps at you.” Others will see “With a grin, CharName jumps at Tommy.”

evennia.utils.funcparser.funcparser_callable_You(*args, you=None, receiver=None, mapping=None, capitalize=True, **kwargs)[source]

Usage: $You() - capitalizes the ‘you’ output.

evennia.utils.funcparser.funcparser_callable_conjugate(*args, caller=None, receiver=None, **kwargs)[source]

Conjugate a verb according to if it should be 2nd or third person.

Keyword Arguments
  • caller (Object) – The object who represents ‘you’ in the string.

  • receiver (Object) – The recipient of the string.

Returns

str – The parsed string.

Raises

ParsingError – If you and recipient were not both supplied.

Notes

Note that the verb will not be capitalized. It also assumes that the active party (You) is the one performing the verb. This automatic conjugation will fail if the active part is another person than ‘you’. The caller/receiver must be passed to the parser directly.

Examples

This is often used in combination with the $you/You( callables.

  • With a grin, $you() $conj(jump)

You will see “With a grin, you jump.” Others will see “With a grin, CharName jumps.”