evennia.typeclasses.attributes

Attributes are arbitrary data stored on objects. Attributes supports both pure-string values and pickled arbitrary data.

Attributes are also used to implement Nicks. This module also contains the Attribute- and NickHandlers as well as the NAttributeHandler, which is a non-db version of Attributes.

class evennia.typeclasses.attributes.IAttribute[source]

Bases: object

Attributes are things that are specific to different types of objects. For example, a drink container needs to store its fill level, whereas an exit needs to store its open/closed/locked/unlocked state. These are done via attributes, rather than making different classes for each object type and storing them directly. The added benefit is that we can add/remove attributes on the fly as we like.

The Attribute class defines the following properties:
  • key (str): Primary identifier.

  • lock_storage (str): Perm strings.

  • model (str): A string defining the model this is connected to. This

    is a natural_key, like “objects.objectdb”

  • date_created (datetime): When the attribute was created.

  • value (any): The data stored in the attribute, in pickled form

    using wrappers to be able to store/retrieve models.

  • strvalue (str): String-only data. This data is not pickled and

    is thus faster to search for in the database.

  • category (str): Optional character string for grouping the

    Attribute.

This class is an API/Interface/Abstract base class; do not instantiate it directly.

locks[source]
property key
property strvalue
property category
property model
property attrtype
property date_created
property lock_storage
access(accessing_obj, access_type='read', default=False, **kwargs)[source]

Determines if another object has permission to access.

Parameters
  • accessing_obj (object) – Entity trying to access this one.

  • access_type (str, optional) – Type of access sought, see the lock documentation.

  • default (bool, optional) – What result to return if no lock of access_type was found. The default, False, means a lockdown policy, only allowing explicit access.

  • kwargs (any, optional) – Not used; here to make the API consistent with other access calls.

Returns

result (bool) – If the lock was passed or not.

class evennia.typeclasses.attributes.InMemoryAttribute(pk, **kwargs)[source]

Bases: evennia.typeclasses.attributes.IAttribute

This Attribute is used purely for NAttributes/NAttributeHandler. It has no database backend.

__init__(pk, **kwargs)[source]

Create an Attribute that exists only in Memory.

Parameters
  • pk (int) – This is a fake ‘primary key’ / id-field. It doesn’t actually have to be unique, but is fed an incrementing number from the InMemoryBackend by default. This is needed only so Attributes can be sorted. Some parts of the API also see the lack of a .pk field as a sign that the Attribute was deleted.

  • **kwargs – Other keyword arguments are used to construct the actual Attribute.

property value
class evennia.typeclasses.attributes.AttributeProperty(default=None, category=None, strattr=False, lockstring='', autocreate=True)[source]

Bases: object

AttributeProperty.

attrhandler_name = 'attributes'
__init__(default=None, category=None, strattr=False, lockstring='', autocreate=True)[source]

Allows for specifying Attributes as Django-like ‘fields’ on the class level. Note that while one can set a lock on the Attribute, there is no way to check said lock when accessing via the property - use the full AttributeHandler if you need to do access checks. Note however that if you use the full AttributeHandler to access this Attribute, the at_get/at_set methods on this class will _not_ fire (because you are bypassing the AttributeProperty entirely in that case).

Initialize an Attribute as a property descriptor.

Keyword Arguments
  • default (any) – A default value if the attr is not set. If a callable, this will be run without any arguments and is expected to return the default value.

  • category (str) – The attribute’s category. If unset, use class default.

  • strattr (bool) – If set, this Attribute must be a simple string, and will be stored more efficiently.

  • lockstring (str) – This is not itself useful with the property, but only if using the full AttributeHandler.get(accessing_obj=…) to access the Attribute.

  • autocreate (bool) – True by default; this means Evennia makes sure to create a new copy of the Attribute (with the default value) whenever a new object with this property is created. If False, no Attribute will be created until the property is explicitly assigned a value. This makes it more efficient while it retains its default (there’s no db access), but without an actual Attribute generated, one cannot access it via .db, the AttributeHandler or see it with examine.

Example:

class Character(DefaultCharacter):
    foo = AttributeProperty(default="Bar")
at_set(value, obj)[source]

The value to set is passed through the method. It can be used to customize/validate the input in a custom child class.

Parameters
  • value (any) – The value about to the stored in this Attribute.

  • obj (object) – Object the attribute is attached to

Returns

any – The value to store.

Raises

AttributeError – If the value is invalid to store.

Notes

This is will only fire if you actually set the Attribute via this AttributeProperty. That is, if you instead set it via the AttributeHandler (or via .db), you are bypassing this AttributeProperty entirely and this method is never reached.

at_get(value, obj)[source]

The value returned from the Attribute is passed through this method. It can be used to react to the retrieval or modify the result in some way.

Parameters
  • value (any) – Value returned from the Attribute.

  • obj (object) – Object the attribute is attached to

Returns

any – The value to return to the caller.

Notes

This is will only fire if you actually get the Attribute via this AttributeProperty. That is, if you instead get it via the AttributeHandler (or via .db), you are bypassing this AttributeProperty entirely and this method is never reached.

class evennia.typeclasses.attributes.NAttributeProperty(default=None, category=None, strattr=False, lockstring='', autocreate=True)[source]

Bases: evennia.typeclasses.attributes.AttributeProperty

NAttribute property descriptor. Allows for specifying NAttributes as Django-like ‘fields’ on the class level.

Example:

class Character(DefaultCharacter):
    foo = NAttributeProperty(default="Bar")
attrhandler_name = 'nattributes'
class evennia.typeclasses.attributes.Attribute(*args, **kwargs)[source]

Bases: evennia.typeclasses.attributes.IAttribute, evennia.utils.idmapper.models.SharedMemoryModel

This attribute is stored via Django. Most Attributes will be using this class.

db_key

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_value

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_strvalue

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_category

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_lock_storage

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_model

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_attrtype

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

db_date_created

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

property lock_storage
property value

Getter. Allows for value = self.value. We cannot cache here since it makes certain cases (such as storing a dbobj which is then deleted elsewhere) out-of-sync. The overhead of unpickling seems hard to avoid.

exception DoesNotExist

Bases: django.core.exceptions.ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: django.core.exceptions.MultipleObjectsReturned

accountdb_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example:

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

**Pizza.toppings** and **Topping.pizzas** are **ManyToManyDescriptor** instances.

Most of the implementation is delegated to a dynamically defined manager class built by **create_forward_many_to_many_manager()** defined below.

property attrtype

A wrapper for getting database field db_attrtype.

property category

A wrapper for getting database field db_category.

channeldb_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example:

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

**Pizza.toppings** and **Topping.pizzas** are **ManyToManyDescriptor** instances.

Most of the implementation is delegated to a dynamically defined manager class built by **create_forward_many_to_many_manager()** defined below.

property date_created

A wrapper for getting database field db_date_created.

get_next_by_db_date_created(*, field=<django.db.models.fields.DateTimeField: db_date_created>, is_next=True, **kwargs)
get_previous_by_db_date_created(*, field=<django.db.models.fields.DateTimeField: db_date_created>, is_next=False, **kwargs)
id

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

property key

A wrapper for getting database field db_key.

property model

A wrapper for getting database field db_model.

objectdb_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example:

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

**Pizza.toppings** and **Topping.pizzas** are **ManyToManyDescriptor** instances.

Most of the implementation is delegated to a dynamically defined manager class built by **create_forward_many_to_many_manager()** defined below.

path = 'evennia.typeclasses.attributes.Attribute'
scriptdb_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example:

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

**Pizza.toppings** and **Topping.pizzas** are **ManyToManyDescriptor** instances.

Most of the implementation is delegated to a dynamically defined manager class built by **create_forward_many_to_many_manager()** defined below.

property strvalue

A wrapper for getting database field db_strvalue.

typename = 'SharedMemoryModelBase'
class evennia.typeclasses.attributes.IAttributeBackend(handler, attrtype)[source]

Bases: object

Abstract interface for the backends used by the Attribute Handler.

All Backends must implement this base class.

__init__(handler, attrtype)[source]

Initialize self. See help(type(self)) for accurate signature.

query_all()[source]

Fetch all Attributes from this object.

Returns

attrlist (list) – A list of Attribute objects.

query_key(key, category)[source]
Parameters
  • key (str) – The key of the Attribute being searched for.

  • category (str or None) – The category of the desired Attribute.

Returns

attribute (IAttribute) – A single Attribute.

query_category(category)[source]

Returns every matching Attribute as a list, given a category.

This method calls up whatever storage the backend uses.

Parameters

category (str or None) – The category to query.

Returns

attrs (list) – The discovered Attributes.

get(key=None, category=None)[source]

Frontend for .get_cache. Retrieves Attribute(s).

Parameters
  • key (str, optional) – Attribute key to query for

  • category (str, optional) – Attribiute category

Returns

args (list)

Returns a list of zero or more matches

found from cache or database.

reset_cache()[source]

Reset cache from the outside.

do_create_attribute(key, category, lockstring, value, strvalue)[source]

Does the hard work of actually creating Attributes, whatever is needed.

Parameters
  • key (str) – The Attribute’s key.

  • category (str or None) – The Attribute’s category, or None

  • lockstring (str) – Any locks for the Attribute.

  • value (obj) – The Value of the Attribute.

  • strvalue (bool) – Signifies if this is a strvalue Attribute. Value MUST be a string or this will lead to Trouble. Ignored for InMemory attributes.

Returns

attr (IAttribute) – The new Attribute.

create_attribute(key, category, lockstring, value, strvalue=False, cache=True)[source]

Creates Attribute (using the class specified for the backend), (optionally) caches it, and returns it.

This MUST actively save the Attribute to whatever database backend is used, AND call self.set_cache(key, category, new_attrobj)

Parameters
  • key (str) – The Attribute’s key.

  • category (str or None) – The Attribute’s category, or None

  • lockstring (str) – Any locks for the Attribute.

  • value (obj) – The Value of the Attribute.

  • strvalue (bool) – Signifies if this is a strvalue Attribute. Value MUST be a string or this will lead to Trouble. Ignored for InMemory attributes.

  • cache (bool) – Whether to cache the new Attribute

Returns

attr (IAttribute) – The new Attribute.

do_update_attribute(attr, value, strvalue)[source]

Simply sets a new Value to an Attribute.

Parameters
  • attr (IAttribute) – The Attribute being changed.

  • value (obj) – The Value for the Attribute.

  • strvalue (bool) – If True, value is expected to be a string.

do_batch_update_attribute(attr_obj, category, lock_storage, new_value, strvalue)[source]

Called opnly by batch add. For the database backend, this is a method of updating that can alter category and lock-storage.

Parameters
  • attr_obj (IAttribute) – The Attribute being altered.

  • category (str or None) – The attribute’s (new) category.

  • lock_storage (str) – The attribute’s new locks.

  • new_value (obj) – The Attribute’s new value.

  • strvalue (bool) – Signifies if this is a strvalue Attribute. Value MUST be a string or this will lead to Trouble. Ignored for InMemory attributes.

do_batch_finish(attr_objs)[source]

Called after batch_add completed. Used for handling database operations and/or caching complications.

Parameters

attr_objs (list of IAttribute) – The Attributes created/updated thus far.

batch_add(*args, **kwargs)[source]

Batch-version of .add(). This is more efficient than repeat-calling .add when having many Attributes to add.

Parameters

*args (tuple) –

Tuples of varying length representing the Attribute to add to this object. Supported tuples are

  • (key, value)

  • (key, value, category)

  • (key, value, category, lockstring)

  • (key, value, category, lockstring, default_access)

Raises

RuntimeError – If trying to pass a non-iterable as argument.

Notes

The indata tuple order matters, so if you want a lockstring but no category, set the category to None. This method does not have the ability to check editing permissions and is mainly used internally. It does not use the normal self.add but applies the Attributes directly to the database.

do_delete_attribute(attr)[source]

Does the hard work of actually deleting things.

Parameters

attr (IAttribute) – The attribute to delete.

delete_attribute(attr)[source]

Given an Attribute, deletes it. Also remove it from cache.

Parameters

attr (IAttribute) – The attribute to delete.

update_attribute(attr, value, strattr=False)[source]

Simply updates an Attribute.

Parameters
  • attr (IAttribute) – The attribute to delete.

  • value (obj) – The new value.

  • strattr (bool) – If set, the value is a raw string.

do_batch_delete(attribute_list)[source]

Given a list of attributes, deletes them all. The default implementation is fine, but this is overridable since some databases may allow for a better method.

Parameters

attribute_list (list of IAttribute) –

clear_attributes(category, accessing_obj, default_access)[source]

Remove all Attributes on this object.

Parameters
  • category (str, optional) – If given, clear only Attributes of this category.

  • accessing_obj (object, optional) – If given, check the attredit lock on each Attribute before continuing.

  • default_access (bool, optional) – Use this permission as fallback if access_obj is given but there is no lock of type attredit on the Attribute in question.

get_all_attributes()[source]

Simply returns all Attributes of this object, sorted by their IDs.

Returns

attributes (list of IAttribute)

class evennia.typeclasses.attributes.InMemoryAttributeBackend(handler, attrtype)[source]

Bases: evennia.typeclasses.attributes.IAttributeBackend

This Backend for Attributes stores NOTHING in the database. Everything is kept in memory, and normally lost on a crash, reload, shared memory flush, etc. It generates IDs for the Attributes it manages, but these are of little importance beyond sorting and satisfying the caching logic to know an Attribute hasn’t been deleted out from under the cache’s nose.

__init__(handler, attrtype)[source]

Initialize self. See help(type(self)) for accurate signature.

query_all()[source]

Fetch all Attributes from this object.

Returns

attrlist (list) – A list of Attribute objects.

query_key(key, category)[source]
Parameters
  • key (str) – The key of the Attribute being searched for.

  • category (str or None) – The category of the desired Attribute.

Returns

attribute (IAttribute) – A single Attribute.

query_category(category)[source]

Returns every matching Attribute as a list, given a category.

This method calls up whatever storage the backend uses.

Parameters

category (str or None) – The category to query.

Returns

attrs (list) – The discovered Attributes.

do_create_attribute(key, category, lockstring, value, strvalue)[source]

See parent class.

strvalue has no meaning for InMemory attributes.

do_update_attribute(attr, value, strvalue)[source]

Simply sets a new Value to an Attribute.

Parameters
  • attr (IAttribute) – The Attribute being changed.

  • value (obj) – The Value for the Attribute.

  • strvalue (bool) – If True, value is expected to be a string.

do_batch_update_attribute(attr_obj, category, lock_storage, new_value, strvalue)[source]

No need to bother saving anything. Just set some values.

do_batch_finish(attr_objs)[source]

Nothing to do here for In-Memory.

Parameters

attr_objs (list of IAttribute) – The Attributes created/updated thus far.

do_delete_attribute(attr)[source]

Removes the Attribute from local storage. Once it’s out of the cache, garbage collection will handle the rest.

Parameters

attr (IAttribute) – The attribute to delete.

class evennia.typeclasses.attributes.ModelAttributeBackend(handler, attrtype)[source]

Bases: evennia.typeclasses.attributes.IAttributeBackend

Uses Django models for storing Attributes.

__init__(handler, attrtype)[source]

Initialize self. See help(type(self)) for accurate signature.

query_all()[source]

Fetch all Attributes from this object.

Returns

attrlist (list) – A list of Attribute objects.

query_key(key, category)[source]
Parameters
  • key (str) – The key of the Attribute being searched for.

  • category (str or None) – The category of the desired Attribute.

Returns

attribute (IAttribute) – A single Attribute.

query_category(category)[source]

Returns every matching Attribute as a list, given a category.

This method calls up whatever storage the backend uses.

Parameters

category (str or None) – The category to query.

Returns

attrs (list) – The discovered Attributes.

do_create_attribute(key, category, lockstring, value, strvalue)[source]

Does the hard work of actually creating Attributes, whatever is needed.

Parameters
  • key (str) – The Attribute’s key.

  • category (str or None) – The Attribute’s category, or None

  • lockstring (str) – Any locks for the Attribute.

  • value (obj) – The Value of the Attribute.

  • strvalue (bool) – Signifies if this is a strvalue Attribute. Value MUST be a string or this will lead to Trouble. Ignored for InMemory attributes.

Returns

attr (IAttribute) – The new Attribute.

do_update_attribute(attr, value, strvalue)[source]

Simply sets a new Value to an Attribute.

Parameters
  • attr (IAttribute) – The Attribute being changed.

  • value (obj) – The Value for the Attribute.

  • strvalue (bool) – If True, value is expected to be a string.

do_batch_update_attribute(attr_obj, category, lock_storage, new_value, strvalue)[source]

Called opnly by batch add. For the database backend, this is a method of updating that can alter category and lock-storage.

Parameters
  • attr_obj (IAttribute) – The Attribute being altered.

  • category (str or None) – The attribute’s (new) category.

  • lock_storage (str) – The attribute’s new locks.

  • new_value (obj) – The Attribute’s new value.

  • strvalue (bool) – Signifies if this is a strvalue Attribute. Value MUST be a string or this will lead to Trouble. Ignored for InMemory attributes.

do_batch_finish(attr_objs)[source]

Called after batch_add completed. Used for handling database operations and/or caching complications.

Parameters

attr_objs (list of IAttribute) – The Attributes created/updated thus far.

do_delete_attribute(attr)[source]

Does the hard work of actually deleting things.

Parameters

attr (IAttribute) – The attribute to delete.

class evennia.typeclasses.attributes.AttributeHandler(obj, backend_class)[source]

Bases: object

Handler for adding Attributes to the object.

__init__(obj, backend_class)[source]

Setup the AttributeHandler.

Parameters

obj (TypedObject) – An Account, Object, Channel, ServerSession (not technically a typed object), etc. backend_class (IAttributeBackend class): The class of the backend to use.

has(key=None, category=None)[source]

Checks if the given Attribute (or list of Attributes) exists on the object.

Parameters
  • key (str or iterable) – The Attribute key or keys to check for. If None, search by category.

  • category (str or None) – Limit the check to Attributes with this category (note, that None is the default category).

Returns

has_attribute (bool or list)

If the Attribute exists on

this object or not. If key was given as an iterable then the return is a list of booleans.

get(key=None, default=None, category=None, return_obj=False, strattr=False, raise_exception=False, accessing_obj=None, default_access=True, return_list=False)[source]

Get the Attribute.

Parameters
  • key (str or list, optional) – the attribute identifier or multiple attributes to get. if a list of keys, the method will return a list.

  • default (any, optional) – The value to return if an Attribute was not defined. If set, it will be returned in a one-item list.

  • category (str, optional) – the category within which to retrieve attribute(s).

  • return_obj (bool, optional) – If set, the return is not the value of the Attribute but the Attribute object itself.

  • strattr (bool, optional) – Return the strvalue field of the Attribute rather than the usual value, this is a string-only value for quick database searches.

  • raise_exception (bool, optional) – When an Attribute is not found, the return from this is usually default. If this is set, an exception is raised instead.

  • accessing_obj (object, optional) – If set, an attrread permission lock will be checked before returning each looked-after Attribute.

  • default_access (bool, optional) – If no attrread lock is set on object, this determines if the lock should then be passed or not.

  • return_list (bool, optional) – Always return a list, also if there is only one or zero matches found.

Returns

result (any or list)

One or more matches for keys and/or

categories. Each match will be the value of the found Attribute(s) unless return_obj is True, at which point it will be the attribute object itself or None. If return_list is True, this will always be a list, regardless of the number of elements.

Raises

AttributeError – If raise_exception is set and no matching Attribute was found matching key.

add(key, value, category=None, lockstring='', strattr=False, accessing_obj=None, default_access=True)[source]

Add attribute to object, with optional lockstring.

Parameters
  • key (str) – An Attribute name to add.

  • value (any or str) – The value of the Attribute. If strattr keyword is set, this must be a string.

  • category (str, optional) – The category for the Attribute. The default None is the normal category used.

  • lockstring (str, optional) – A lock string limiting access to the attribute.

  • strattr (bool, optional) – Make this a string-only Attribute. This is only ever useful for optimization purposes.

  • accessing_obj (object, optional) – An entity to check for the attrcreate access-type. If not passing, this method will be exited.

  • default_access (bool, optional) – What access to grant if accessing_obj is given but no lock of the type attrcreate is defined on the Attribute in question.

batch_add(*args, **kwargs)[source]

Batch-version of add(). This is more efficient than repeat-calling add when having many Attributes to add.

Parameters

*args (tuple) –

Each argument should be a tuples (can be of varying length) representing the Attribute to add to this object. Supported tuples are

  • (key, value)

  • (key, value, category)

  • (key, value, category, lockstring)

  • (key, value, category, lockstring, default_access)

Keyword Arguments

strattr (bool) – If True, value must be a string. This will save the value without pickling which is less flexible but faster to search (not often used except internally).

Raises

RuntimeError – If trying to pass a non-iterable as argument.

Notes

The indata tuple order matters, so if you want a lockstring but no category, set the category to None. This method does not have the ability to check editing permissions like normal .add does, and is mainly used internally. It does not use the normal self.add but apply the Attributes directly to the database.

remove(key=None, category=None, raise_exception=False, accessing_obj=None, default_access=True)[source]

Remove attribute or a list of attributes from object.

Parameters
  • key (str or list, optional) – An Attribute key to remove or a list of keys. If multiple keys, they must all be of the same category. If None and category is not given, remove all Attributes.

  • category (str, optional) – The category within which to remove the Attribute.

  • raise_exception (bool, optional) – If set, not finding the Attribute to delete will raise an exception instead of just quietly failing.

  • accessing_obj (object, optional) – An object to check against the attredit lock. If not given, the check will be skipped.

  • default_access (bool, optional) – The fallback access to grant if accessing_obj is given but there is no attredit lock set on the Attribute in question.

Raises

AttributeError – If raise_exception is set and no matching Attribute was found matching key.

Notes

If neither key nor category is given, this acts as clear().

clear(category=None, accessing_obj=None, default_access=True)[source]

Remove all Attributes on this object.

Parameters
  • category (str, optional) – If given, clear only Attributes of this category.

  • accessing_obj (object, optional) – If given, check the attredit lock on each Attribute before continuing.

  • default_access (bool, optional) – Use this permission as fallback if access_obj is given but there is no lock of type attredit on the Attribute in question.

all(category=None, accessing_obj=None, default_access=True)[source]

Return all Attribute objects on this object, regardless of category.

Parameters
  • category (str, optional) – A given category to limit results to.

  • accessing_obj (object, optional) – Check the attrread lock on each attribute before returning them. If not given, this check is skipped.

  • default_access (bool, optional) – Use this permission as a fallback if accessing_obj is given but one or more Attributes has no lock of type attrread defined on them.

Returns

Attributes (list)

All the Attribute objects (note: Not

their values!) in the handler.

reset_cache()[source]
class evennia.typeclasses.attributes.DbHolder(obj, name, manager_name='attributes')[source]

Bases: object

Holder for allowing property access of attributes

__init__(obj, name, manager_name='attributes')[source]

Initialize self. See help(type(self)) for accurate signature.

get_all()[source]
property all
exception evennia.typeclasses.attributes.NickTemplateInvalid[source]

Bases: ValueError

evennia.typeclasses.attributes.initialize_nick_templates(pattern, replacement, pattern_is_regex=False)[source]

Initialize the nick templates for matching and remapping a string.

Parameters
  • pattern (str) – The pattern to be used for nick recognition. This will be parsed for shell patterns into a regex, unless pattern_is_regex is True, in which case it must be an already valid regex string. In this case, instead of $N, numbered arguments must instead be given as matching groups named as argN, such as (?P<arg1>.+?).

  • replacement (str) – The template to be used to replace the string matched by the pattern. This can contain $N markers and is never parsed into a regex.

  • pattern_is_regex (bool) – If set, pattern is a full regex string instead of containing shell patterns.

Returns

regex, template (str)

Regex to match against strings and template

with markers **{arg1}, {arg2}**, etc for replacement using the standard .format method.

Raises
  • evennia.typecalasses.attributes.NickTemplateInvalid – If the in/out

  • template does not have a matching number of $args.

Examples

  • pattern (shell syntax): “grin $1”

  • pattern (regex): “grin (?P<arg1.+?>)”

  • replacement: “emote gives a wicked grin to $1”

evennia.typeclasses.attributes.parse_nick_template(string, template_regex, outtemplate)[source]

Parse a text using a template and map it to another template

Parameters
  • string (str) – The input string to process

  • template_regex (regex) – A template regex created with initialize_nick_template.

  • outtemplate (str) – The template to which to map the matches produced by the template_regex. This should have $1, $2, etc to match the template-regex. Un-found $N-markers (possible if the regex has optional matching groups) are replaced with empty strings.

class evennia.typeclasses.attributes.NickHandler(*args, **kwargs)[source]

Bases: evennia.typeclasses.attributes.AttributeHandler

Handles the addition and removal of Nicks. Nicks are special versions of Attributes with an _attrtype hardcoded to nick. They also always use the strvalue fields for their data.

__init__(*args, **kwargs)[source]

Setup the AttributeHandler.

Parameters

obj (TypedObject) – An Account, Object, Channel, ServerSession (not technically a typed object), etc. backend_class (IAttributeBackend class): The class of the backend to use.

has(key, category='inputline')[source]
Parameters
  • key (str or iterable) – The Nick key or keys to check for.

  • category (str) – Limit the check to Nicks with this category (note, that None is the default category).

Returns

has_nick (bool or list)

If the Nick exists on this object

or not. If key was given as an iterable then the return is a list of booleans.

get(key=None, category='inputline', return_tuple=False, **kwargs)[source]

Get the replacement value matching the given key and category

Parameters
  • key (str or list, optional) – the attribute identifier or multiple attributes to get. if a list of keys, the method will return a list.

  • category (str, optional) – the category within which to retrieve the nick. The “inputline” means replacing data sent by the user.

  • return_tuple (bool, optional) – return the full nick tuple rather than just the replacement. For non-template nicks this is just a string.

  • kwargs (any, optional) – These are passed on to AttributeHandler.get.

Returns

str or tuple – The nick replacement string or nick tuple.

add(pattern, replacement, category='inputline', pattern_is_regex=False, **kwargs)[source]

Add a new nick, a mapping pattern -> replacement.

Parameters
  • pattern (str) – A pattern to match for. This will be parsed for shell patterns using the fnmatch library and can contain $N-markers to indicate the locations of arguments to catch. If pattern_is_regex=True, this must instead be a valid regular expression and the $N-markers must be named argN that matches numbered regex groups (see examples).

  • replacement (str) – The string (or template) to replace key with (the “nickname”). This may contain $N markers to indicate where to place the argument-matches

  • category (str, optional) – the category within which to retrieve the nick. The “inputline” means replacing data sent by the user.

  • pattern_is_regex (bool) – If True, the pattern will be parsed as a raw regex string. Instead of using $N markers in this string, one then must mark numbered arguments as a named regex-groupd named argN. For example, (?P<arg1>.+?) will match the behavior of using $1 in the shell pattern.

  • **kwargs (any, optional) – These are passed on to AttributeHandler.get.

Notes

For most cases, the shell-pattern is much shorter and easier. The regex pattern form can be useful for more complex matchings though, for example in order to add optional arguments, such as with (?P<argN>.*?).

Example

  • pattern (default shell syntax): “gr $1 at $2”

  • pattern (with pattern_is_regex=True): r”gr (?P<arg1>.+?) at (?P<arg2>.+?)”

  • replacement: “emote With a flourish, $1 grins at $2.”

remove(key, category='inputline', **kwargs)[source]

Remove Nick with matching category.

Parameters
  • key (str) – A key for the nick to match for.

  • category (str, optional) – the category within which to removethe nick. The “inputline” means replacing data sent by the user.

  • kwargs (any, optional) – These are passed on to AttributeHandler.get.

nickreplace(raw_string, categories='inputline', 'channel', include_account=True)[source]

Apply nick replacement of entries in raw_string with nick replacement.

Parameters
  • raw_string (str) – The string in which to perform nick replacement.

  • categories (tuple, optional) – Replacement categories in which to perform the replacement, such as “inputline”, “channel” etc.

  • include_account (bool, optional) – Also include replacement with nicks stored on the Account level.

  • kwargs (any, optional) – Not used.

Returns

string (str)

A string with matching keys replaced with

their nick equivalents.