evennia.typeclasses.models

This is the abstract django models for many of the database objects in Evennia. A django abstract (obs, not the same as a Python metaclass!) is a model which is not actually created in the database, but which only exists for other models to inherit from, to avoid code duplication. Any model can import and inherit from these classes.

Attributes are database objects stored on other objects. The implementing class needs to supply a ForeignKey field attr_object pointing to the kind of object being mapped. Attributes storing iterables actually store special types of iterables named PackedList/PackedDict respectively. These make sure to save changes to them to database - this is criticial in order to allow for obj.db.mylist[2] = data. Also, all dbobjects are saved as dbrefs but are also aggressively cached.

TypedObjects are objects ‘decorated’ with a typeclass - that is, the typeclass (which is a normal Python class implementing some special tricks with its get/set attribute methods, allows for the creation of all sorts of different objects all with the same database object underneath. Usually attributes are used to permanently store things not hard-coded as field on the database object. The admin should usually not have to deal directly with the database object layer.

This module also contains the Managers for the respective models; inherit from these to create custom managers.

class evennia.typeclasses.models.TypedObject(*args, **kwargs)[source]

Bases: SharedMemoryModel

Abstract Django model.

This is the basis for a typed object. It also contains all the mechanics for managing connected attributes.

The TypedObject has the following properties:

  • key - main name

  • name - alias for key

  • typeclass_path - the path to the decorating typeclass

  • typeclass - auto-linked typeclass

  • date_created - time stamp of object creation

  • permissions - perm strings

  • dbref - #id of object

  • db - persistent attribute storage

  • ndb - non-persistent attribute storage

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_typeclass_path

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.

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_attributes

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.

db_tags

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.

objects
set_class_from_typeclass(typeclass_path=None)[source]
__init__(*args, **kwargs)[source]

The __init__ method of typeclasses is the core operational code of the typeclass system, where it dynamically re-applies a class based on the db_typeclass_path database field rather than use the one in the model.

Parameters:

parent. (Passed through to)

Keyword Arguments:

parent. (Passed through to)

Notes

The loading mechanism will attempt the following steps:

  1. Attempt to load typeclass given on command line

  2. Attempt to load typeclass stored in db_typeclass_path

  3. Attempt to load __settingsclasspath__, which is by the default classes defined to be the respective user-set base typeclass settings, like BASE_OBJECT_TYPECLASS.

  4. Attempt to load __defaultclasspath__, which is the base classes in the library, like DefaultObject etc.

  5. If everything else fails, use the database model.

Normal operation is to load successfully at either step 1 or 2 depending on how the class was called. Tracebacks will be logged for every step the loader must take beyond 2.

init_evennia_properties()[source]

Called by creation methods; makes sure to initialize Attribute/TagProperties by fetching them once.

attributes[source]
locks[source]
tags[source]
aliases[source]
permissions[source]
nattributes[source]
class Meta[source]

Bases: object

Django setup info.

abstract = False
verbose_name = 'Evennia Database Object'
ordering = ['-db_date_created', 'id', 'db_typeclass_path', 'db_key']
property name
property key
property date_created

Get the localized date created, based on settings.TIME_ZONE.

property dbid

Caches and returns the unique id of the object. Use this instead of self.id, which is not cached.

property dbref

Returns the object’s dbref on the form #NN.

at_idmapper_flush()[source]

This is called when the idmapper cache is flushed and allows customized actions when this happens.

Returns:

do_flush (bool)

If True, flush this object as normal. If

False, don’t flush and expect this object to handle the flushing on its own.

Notes

The default implementation relies on being able to clear Django’s Foreignkey cache on objects not affected by the flush (notably objects with an NAttribute stored). We rely on this cache being stored on the format “_<fieldname>_cache”. If Django were to change this name internally, we need to update here (unlikely, but marking just in case).

at_init()[source]

Called when this object is loaded into cache. This is more reliable than to override __init__.

classmethod search(query, **kwargs)[source]

Overridden by class children. This implements a common API.

Parameters:
  • query (str) – A search query.

  • **kwargs – Other search parameters.

Returns:

list – A list of 0, 1 or more matches, only of this typeclass.

is_typeclass(typeclass, exact=False)[source]

Returns true if this object has this type OR has a typeclass which is an subclass of the given typeclass. This operates on the actually loaded typeclass (this is important since a failing typeclass may instead have its default currently loaded) typeclass - can be a class object or the python path to such an object to match against.

Parameters:
  • typeclass (str or class) – A class or the full python path to the class to check.

  • exact (bool, optional) – Returns true only if the object’s type is exactly this typeclass, ignoring parents.

Returns:

is_typeclass (bool)

If this typeclass matches the given

typeclass.

swap_typeclass(new_typeclass, clean_attributes=False, run_start_hooks='all', no_default=True, clean_cmdsets=False)[source]

This performs an in-situ swap of the typeclass. This means that in-game, this object will suddenly be something else. Account will not be affected. To ‘move’ an account to a different object entirely (while retaining this object’s type), use self.account.swap_object().

Note that this might be an error prone operation if the old/new typeclass was heavily customized - your code might expect one and not the other, so be careful to bug test your code if using this feature! Often its easiest to create a new object and just swap the account over to that one instead.

Parameters:
  • new_typeclass (str or classobj) – Type to switch to.

  • clean_attributes (bool or list, optional) – Will delete all attributes stored on this object (but not any of the database fields such as name or location). You can’t get attributes back, but this is often the safest bet to make sure nothing in the new typeclass clashes with the old one. If you supply a list, only those named attributes will be cleared.

  • run_start_hooks (str or None, optional) – This is either None, to not run any hooks, “all” to run all hooks defined by at_first_start, or a string with space-separated hook-names to run (for example ‘at_object_creation’). This will always be called without arguments.

  • no_default (bool, optiona) – If set, the swapper will not allow for swapping to a default typeclass in case the given one fails for some reason. Instead the old one will be preserved.

  • clean_cmdsets (bool, optional) – Delete all cmdsets on the object.

access(accessing_obj, access_type='read', default=False, no_superuser_bypass=False, **kwargs)[source]

Determines if another object has permission to access this one.

Parameters:
  • accessing_obj (str) – Object trying to access this one.

  • access_type (str, optional) – Type of access sought.

  • default (bool, optional) – What to return if no lock of access_type was found

  • no_superuser_bypass (bool, optional) – Turn off the superuser lock bypass (be careful with this one).

Keyword Arguments:

kwar (any) – Ignored, but is there to make the api consistent with the object-typeclass method access, which use it to feed to its hook methods.

check_permstring(permstring)[source]

This explicitly checks if we hold particular permission without involving any locks.

Parameters:

permstring (str) – The permission string to check against.

Returns:

result (bool) – If the permstring is passed or not.

delete()[source]

Cleaning up handlers on the typeclass level

property db

Attribute handler wrapper. Allows for the syntax

obj.db.attrname = value
# and
value = obj.db.attrname
# and
del obj.db.attrname
# and
all_attr = obj.db.all()
# (unless there is an attribute
#  named 'all', in which case that will be returned instead).
property ndb

NonDataBase). Everything stored to this is guaranteed to be cleared when a server is shutdown. Syntax is same as for the _get_db_holder() method and property, e.g. obj.ndb.attr = value etc.

Type:

A non-attr_obj store (ndb

get_display_name(looker, **kwargs)[source]

Displays the name of the object in a viewer-aware manner.

Parameters:

looker (TypedObject, optional) – The object or account that is looking at/getting inforamtion for this object. If not given, some ‘safe’ minimum level should be returned.

Returns:

name (str)

A string containing the name of the object,

including the DBREF if this user is privileged to control said object.

Notes

This function could be extended to change how object names appear to users in character, but be wary. This function does not change an object’s keys or aliases when searching, and is expected to produce something useful for builders.

get_extra_info(looker, **kwargs)[source]

Used when an object is in a list of ambiguous objects as an additional information tag.

For instance, if you had potions which could have varying levels of liquid left in them, you might want to display how many drinks are left in each when selecting which to drop, but not in your normal inventory listing.

Parameters:

looker (TypedObject) – The object or account that is looking at/getting information for this object.

Returns:

info (str)

A string with disambiguating information,

conventionally with a leading space.

at_rename(oldname, newname)[source]

This Hook is called by @name on a successful rename.

Parameters:
  • oldname (str) – The instance’s original name.

  • newname (str) – The new name for the instance.

web_get_admin_url()[source]

Returns the URI path for the Django Admin page for this object.

ex. Account#1 = ‘/admin/accounts/accountdb/1/change/’

Returns:

path (str) – URI path to Django Admin page for object.

classmethod web_get_create_url()[source]

Returns the URI path for a View that allows users to create new instances of this object.

ex. Chargen = ‘/characters/create/’

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-create’ would be referenced by this method.

ex. url(r’characters/create/’, ChargenView.as_view(), name=’character-create’)

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can create new objects is the developer’s responsibility.

Returns:

path (str) – URI path to object creation page, if defined.

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)
property lock_storage

A wrapper for getting database field db_lock_storage.

path = 'evennia.typeclasses.models.TypedObject'
property typeclass_path

A wrapper for getting database field db_typeclass_path.

typename = 'SharedMemoryModelBase'
web_get_detail_url()[source]

Returns the URI path for a View that allows users to view details for this object.

Returns:

path (str) – URI path to object detail page, if defined.

Examples

Oscar (Character) = '/characters/oscar/1/'

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-detail’ would be referenced by this method.

url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/$',
    CharDetailView.as_view(), name='character-detail')

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can view this object is the developer’s responsibility.

web_get_puppet_url()[source]

Returns the URI path for a View that allows users to puppet a specific object.

Returns:

str – URI path to object puppet page, if defined.

Examples

Oscar (Character) = '/characters/oscar/1/puppet/'

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-puppet’ would be referenced by this method.

url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/puppet/$',
    CharPuppetView.as_view(), name='character-puppet')

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can view this object is the developer’s responsibility.

web_get_update_url()[source]

Returns the URI path for a View that allows users to update this object.

Returns:

str – URI path to object update page, if defined.

Examples

Oscar (Character) = '/characters/oscar/1/change/'

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-update’ would be referenced by this method.

url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/change/$',
CharUpdateView.as_view(), name='character-update')

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can modify objects is the developer’s responsibility.

web_get_delete_url()[source]

Returns the URI path for a View that allows users to delete this object.

Returns:

path (str) – URI path to object deletion page, if defined.

Examples

Oscar (Character) = '/characters/oscar/1/delete/'

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-detail’ would be referenced by this method.

url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/delete/$',
CharDeleteView.as_view(), name='character-delete')

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can delete this object is the developer’s responsibility.

get_absolute_url()

Returns the URI path for a View that allows users to view details for this object.

Returns:

path (str) – URI path to object detail page, if defined.

Examples

Oscar (Character) = '/characters/oscar/1/'

For this to work, the developer must have defined a named view somewhere in urls.py that follows the format ‘modelname-action’, so in this case a named view of ‘character-detail’ would be referenced by this method.

url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/$',
    CharDetailView.as_view(), name='character-detail')

If no View has been created and defined in urls.py, returns an HTML anchor.

This method is naive and simply returns a path. Securing access to the actual view and limiting who can view this object is the developer’s responsibility.

class evennia.typeclasses.models.AliasHandler(obj)[source]

Bases: TagHandler

A handler for the Alias Tag type.

class evennia.typeclasses.models.Attribute(*args, **kwargs)[source]

Bases: IAttribute, SharedMemoryModel

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

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: 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.

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_category

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.

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_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_strvalue

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.

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 lock_storage
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'
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.

class evennia.typeclasses.models.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.

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.

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.

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.

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.

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.

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.

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

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

Bases: object

AttributeProperty.

__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_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.

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.

attrhandler_name = 'attributes'
cached_default_name_template = '_property_attribute_default_{key}'
class evennia.typeclasses.models.ContentType(id, app_label, model)[source]

Bases: Model

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

app_label

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

property app_labeled_name
get_all_objects_for_this_type(**kwargs)[source]

Return all objects of this type for the keyword arguments given.

get_object_for_this_type(using=None, **kwargs)[source]

Return an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type’s get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it.

id

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

logentry_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

**Parent.children** is a **ReverseManyToOneDescriptor** instance.

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

model

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

model_class()[source]

Return the model class for this type of content.

property name
natural_key()[source]
objects = <django.contrib.contenttypes.models.ContentTypeManager object>
permission_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example:

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

**Parent.children** is a **ReverseManyToOneDescriptor** instance.

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

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

Bases: object

Holder for allowing property access of attributes

__init__(obj, name, manager_name='attributes')[source]
property all
get_all()[source]
class evennia.typeclasses.models.InMemoryAttributeBackend(handler, attrtype)[source]

Bases: 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]
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_batch_update_attribute(attr_obj, category, lock_storage, new_value, strvalue)[source]

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

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

See parent class.

strvalue has no meaning for InMemory attributes.

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.

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.

query_all()[source]

Fetch all Attributes from this object.

Returns:

attrlist (list) – A list of Attribute objects.

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.

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.

class evennia.typeclasses.models.LockHandler(obj)[source]

Bases: object

This handler should be attached to all objects implementing permission checks, under the property ‘lockhandler’.

__init__(obj)[source]

Loads and pre-caches all relevant locks and their functions.

Parameters:
  • obj (object) – The object on which the lockhandler is

  • defined.

add(lockstring, validate_only=False)[source]

Add a new lockstring to handler.

Parameters:
  • lockstring (str or list) – A string on the form “<access_type>:<functions>”. Multiple access types should be separated by semicolon (;). Alternatively, a list with lockstrings.

  • validate_only (bool, optional) – If True, validate the lockstring but don’t actually store it.

Returns:

success (bool)

The outcome of the addition, False on

error. If validate_only is True, this will be a tuple (bool, error), for pass/fail and a string error.

all()[source]

Return all lockstrings

Returns:

lockstrings (list) – All separate lockstrings

append(access_type, lockstring, op='or')[source]

Append a lock definition to access_type if it doesn’t already exist.

Parameters:
  • access_type (str) – Access type.

  • lockstring (str) – A valid lockstring, without the operator to link it to an eventual existing lockstring.

  • op (str) – An operator ‘and’, ‘or’, ‘and not’, ‘or not’ used for appending the lockstring to an existing access-type.

Note

The most common use of this method is for use in commands where the user can specify their own lockstrings. This method allows the system to auto-add things like Admin-override access.

cache_lock_bypass(obj)[source]

We cache superuser bypass checks here for efficiency. This needs to be re-run when an account is assigned to a character. We need to grant access to superusers. We need to check both directly on the object (accounts), through obj.account and using the get_account() method (this sits on serversessions, in some rare cases where a check is done before the login process has yet been fully finalized)

Parameters:

obj (object) – This is checked for the is_superuser property.

check(accessing_obj, access_type, default=False, no_superuser_bypass=False)[source]

Checks a lock of the correct type by passing execution off to the lock function(s).

Parameters:
  • accessing_obj (object) – The object seeking access.

  • access_type (str) – The type of access wanted.

  • default (bool, optional) – If no suitable lock type is found, default to this result.

  • no_superuser_bypass (bool) – Don’t use this unless you really, really need to, it makes supersusers susceptible to the lock check.

Notes

A lock is executed in the follwoing way:

Parsing the lockstring, we (during cache) extract the valid lock functions and store their function objects in the right order along with their args/kwargs. These are now executed in sequence, creating a list of True/False values. This is put into the evalstring, which is a string of AND/OR/NOT entries separated by placeholders where each function result should go. We just put those results in and evaluate the string to get a final, combined True/False value for the lockstring.

The important bit with this solution is that the full lockstring is never blindly evaluated, and thus there (should be) no way to sneak in malign code in it. Only “safe” lock functions (as defined by your settings) are executed.

check_lockstring(accessing_obj, lockstring, no_superuser_bypass=False, default=False, access_type=None)[source]

Do a direct check against a lockstring (‘atype:func()..’), without any intermediary storage on the accessed object.

Parameters:
  • accessing_obj (object or None) – The object seeking access. Importantly, this can be left unset if the lock functions don’t access it, no updating or storage of locks are made against this object in this method.

  • lockstring (str) – Lock string to check, on the form “access_type:lock_definition” where the access_type part can potentially be set to a dummy value to just check a lock condition.

  • no_superuser_bypass (bool, optional) – Force superusers to heed lock.

  • default (bool, optional) – Fallback result to use if access_type is set but no such access_type is found in the given lockstring.

  • access_type (str, bool) – If set, only this access_type will be looked up among the locks defined by lockstring.

Returns:

access (bool) – If check is passed or not.

clear()[source]

Remove all locks in the handler.

delete(access_type)

Remove a particular lock from the handler

Parameters:

access_type (str) – The type of lock to remove.

Returns:

success (bool)

If the access_type was not found

in the lock, this returns False.

get(access_type=None)[source]

Get the full lockstring or the lockstring of a particular access type.

Parameters:

access_type (str, optional)

Returns:

lockstring (str)

The matched lockstring, or the full

lockstring if no access_type was given.

remove(access_type)[source]

Remove a particular lock from the handler

Parameters:

access_type (str) – The type of lock to remove.

Returns:

success (bool)

If the access_type was not found

in the lock, this returns False.

replace(lockstring)[source]

Replaces the lockstring entirely.

Parameters:

lockstring (str) – The new lock definition.

Returns:

success (bool) – False if an error occurred.

Raises:

LockException – If a critical error occurred. If so, the old string is recovered.

reset()[source]

Set the reset flag, so the the lock will be re-cached at next checking. This is usually called by @reload.

validate(lockstring)[source]

Validate lockstring syntactically, without saving it.

Parameters:

lockstring (str) – Lockstring to validate.

Returns:

valid (bool) – If validation passed or not.

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

Bases: IAttributeBackend

Uses Django models for storing Attributes.

__init__(handler, attrtype)[source]
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_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_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_delete_attribute(attr)[source]

Does the hard work of actually deleting things.

Parameters:

attr (IAttribute) – The attribute to delete.

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.

query_all()[source]

Fetch all Attributes from this object.

Returns:

attrlist (list) – A list of Attribute objects.

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.

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.

class evennia.typeclasses.models.ModelBase(name, bases, attrs, **kwargs)[source]

Bases: type

Metaclass for all models.

add_to_class(name, value)[source]
exception evennia.typeclasses.models.ObjectDoesNotExist[source]

Bases: Exception

The requested object does not exist

silent_variable_failure = True
class evennia.typeclasses.models.PermissionHandler(obj)[source]

Bases: TagHandler

A handler for the Permission Tag type.

check(*permissions, require_all=False)[source]

Straight-up check the provided permission against this handler. The check will pass if

  • any/all given permission exists on the handler (depending on if require_all is set).

  • If handler sits on puppeted object and this is a hierarachical perm, the puppeting Account’s permission will also be included in the check, prioritizing the Account’s perm (this avoids escalation exploits by puppeting a too-high prio character)

  • a permission is also considered to exist on the handler, if it is lower than a permission on the handler and this is a ‘hierarchical’ permission given in settings.PERMISSION_HIERARCHY. Example: If the ‘Developer’ hierarchical perm perm is set on the handler, and we check for the ‘Builder’ perm, the check will pass.

Parameters:
  • *permissions (str) – Any number of permissions to check. By default, the permission is passed if any of these (or higher, if a hierarchical permission defined in settings.PERMISSION_HIERARCHY) exists in the handler. Permissions are not case-sensitive.

  • require_all (bool) – If set, all provided permissions much pass the check for the entire check to pass. By default only one needs to pass.

Returns:

bool – If the provided permission(s) pass the check on this handler.

Example

::

can_enter = obj.permissions.check(“Blacksmith”, “Builder”)

Notes

This works the same way as the perms lockfunc and could be replicated with a lock check against the lockstring

“locktype: perm(perm1) OR perm(perm2) OR …”

(using AND for the require_all condition).

class evennia.typeclasses.models.SharedMemoryModel(*args, **kwargs)[source]

Bases: Model

Base class for idmapped objects. Inherit from this.

class Meta[source]

Bases: object

abstract = False
at_idmapper_flush()[source]

This is called when the idmapper cache is flushed and allows customized actions when this happens.

Returns:

do_flush (bool)

If True, flush this object as normal. If

False, don’t flush and expect this object to handle the flushing on its own.

classmethod cache_instance(instance, new=False)[source]

Method to store an instance in the cache.

Parameters:
  • instance (Class instance) – the instance to cache.

  • new (bool, optional) – this is the first time this instance is cached (i.e. this is not an update operation like after a db save).

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

Delete the object, clearing cache.

classmethod flush_cached_instance(instance, force=True)[source]

Method to flush an instance from the cache. The instance will always be flushed from the cache, since this is most likely called from delete(), and we want to make sure we don’t cache dead objects.

flush_from_cache(force=False)[source]

Flush this instance from the instance cache. Use force to override the result of at_idmapper_flush() for the object.

classmethod flush_instance_cache(force=False)[source]

This will clean safe objects from the cache. Use force keyword to remove all objects, safe or not.

classmethod get_all_cached_instances()[source]

Return the objects so far cached by idmapper for this class.

classmethod get_cached_instance(id)[source]

Method to retrieve a cached instance by pk value. Returns None when not found (which will always be the case when caching is disabled for this class). Please note that the lookup will be done even when instance caching is disabled.

objects
path = 'evennia.utils.idmapper.models.SharedMemoryModel'
save(*args, **kwargs)[source]

Central database save operation.

Notes

Arguments as per Django documentation. Calls self.at_<fieldname>_postsave(new) (this is a wrapper set by oobhandler: self._oob_at_<fieldname>_postsave())

typename = 'SharedMemoryModelBase'
class evennia.typeclasses.models.SharedMemoryModelBase(name, bases, attrs)[source]

Bases: ModelBase

class evennia.typeclasses.models.Tag(*args, **kwargs)[source]

Bases: Model

Tags are quick markers for objects in-game. An typeobject can have any number of tags, stored via its db_tags property. Tagging similar objects will make it easier to quickly locate the group later (such as when implementing zones). The main advantage of tagging as opposed to using tags is speed; a tag is very limited in what data it can hold, and the tag key+category is indexed for efficient lookup in the database. Tags are shared between objects - a new tag is only created if the key+category combination did not previously exist, making them unsuitable for storing object-related data (for this a regular Attribute should be used).

The ‘db_data’ field is intended as a documentation field for the tag itself, such as to document what this tag+category stands for and display that in a web interface or similar.

The main default use for Tags is to implement Aliases for objects. this uses the ‘aliases’ tag category, which is also checked by the default search functions of Evennia to allow quick searches by alias.

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: 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.

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.

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_data

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

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_model

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

db_tagtype

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

helpentry_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.

id

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

msg_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.

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.

objects = <django.db.models.manager.Manager object>
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.

class evennia.typeclasses.models.TagCategoryProperty(*default_tags)[source]

Bases: object

Tag Category Property.

__init__(*default_tags)[source]

Assign a property for a Tag Category, with any number of Tag keys. This is often more useful than the TagProperty since it’s common to want to check which tags of a particular category the object is a member of.

Parameters:

*args (str or callable) – Tag keys to assign to this property, using the category given by the name of the property. Note that, if these tags are always set on the object, if they are removed by some other means, they will be re-added when this property is accessed. Furthermore, changing this list after the object was created, will not remove any old tags (there is no way for the property to know if the new list is new or not). If a callable, it will be called without arguments to return the tag key. It is not possible to set tag data this way (use the Taghandler directly for that). Tag keys are not case sensitive.

Raises:

ValueError – If the input is not a valid tag key or tuple.

Notes

It is not possible to set Tags with a None category using a TagCategoryProperty - use obj.tags.add() instead.

Example:

class RogueCharacter(DefaultCharacter):
    guild = TagCategoryProperty("thieves_guild", "merchant_guild")
taghandler_name = 'tags'
class evennia.typeclasses.models.TagHandler(obj)[source]

Bases: object

Generic tag-handler. Accessed via TypedObject.tags.

__init__(obj)[source]

Tags are stored internally in the TypedObject.db_tags m2m field with an tag.db_model based on the obj the taghandler is stored on and with a tagtype given by self.handlertype

Parameters:

obj (object) – The object on which the handler is set.

add(key=None, category=None, data=None)[source]

Add a new tag to the handler.

Parameters:
  • key (str or list) – The name of the tag to add. If a list, add several Tags.

  • category (str, optional) – Category of Tag. None is the default category.

  • data (str, optional) – Info text about the tag(s) added. This can not be used to store object-unique info but only eventual info about the tag itself.

Notes

If the tag + category combination matches an already existing Tag object, this will be re-used and no new Tag will be created.

all(return_key_and_category=False, return_objs=False)[source]

Get all tags in this handler, regardless of category.

Parameters:
  • return_key_and_category (bool, optional) – Return a list of tuples [(key, category), …].

  • return_objs (bool, optional) – Return tag objects.

Returns:

tags (list)

A list of tag keys [tagkey, tagkey, …] or

a list of tuples [(key, category), …] if return_key_and_category is set.

batch_add(*args)[source]

Batch-add tags from a list of tuples.

Parameters:

*args (tuple or str) – Each argument should be a tagstr keys or tuple (keystr, category) or (keystr, category, data). It’s possible to mix input types.

Notes

This will generate a mimimal number of self.add calls, based on the number of categories involved (including None) (data is not unique and may be overwritten by the content of a latter tuple with the same category).

batch_remove(*args)[source]

Batch-remove tags from a list of tuples.

Parameters:

*args (tuple or str) – Each argument should be a tagstr keys or tuple (keystr, category) or (keystr, category, data) (the data field is ignored, only keystr/category matters). It’s possible to mix input types.

clear(category=None)[source]

Remove all tags from the handler.

Parameters:

category (str, optional) – The Tag category to limit the request to. Note that None is the valid, default category.

get(key=None, default=None, category=None, return_tagobj=False, return_list=False, raise_exception=False)[source]

Get the tag for the given key, category or combination of the two.

Parameters:
  • key (str or list, optional) – The tag or tags to retrieve.

  • default (any, optional) – The value to return in case of no match.

  • category (str, optional) – The Tag category to limit the request to. Note that None is the valid, default category. If no key is given, all tags of this category will be returned.

  • return_tagobj (bool, optional) – Return the Tag object itself instead of a string representation of the Tag.

  • return_list (bool, optional) – Always return a list, regardless of number of matches.

  • raise_exception (bool, optional) – Raise AttributeError if no matches are found.

Returns:

tags (list)

The matches, either string

representations of the tags or the Tag objects themselves depending on return_tagobj. If ‘default’ is set, this will be a list with the default value as its only element.

Raises:

AttributeError – If finding no matches and raise_exception is True.

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

Checks if the given Tag (or list of Tags) exists on the object.

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

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

Returns:

has_tag (bool or list)

If the Tag exists on this object or not.

If tag was given as an iterable then the return is a list of booleans.

Raises:

ValueError – If neither tag nor category is given.

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

Remove a tag from the handler based ond key and/or category.

Parameters:
  • key (str or list, optional) – The tag or tags to retrieve.

  • category (str, optional) – The Tag category to limit the request to. Note that None is the valid, default category

Notes

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

reset_cache()[source]

Reset the cache from the outside.

class evennia.typeclasses.models.TagProperty(category=None, data=None)[source]

Bases: object

Tag Property.

__init__(category=None, data=None)[source]

Tag property descriptor. Allows for setting tags on an object as Django-like ‘fields’ on the class level. Since Tags are almost always used for querying, Tags are always created/assigned along with the object. Make sure the property/tagname does not collide with an existing method/property on the class. If it does, you must use tags.add() instead.

Note that while you _can_ check e.g. obj.tagname,this will give an AttributeError if the Tag is not set. Most often you want to use **obj.tags.get(“tagname”) to check if a tag is set on an object.

Example:

class Character(DefaultCharacter):
    mytag = TagProperty()  # category=None
    mytag2 = TagProperty(category="tagcategory")
taghandler_name = 'tags'
class evennia.typeclasses.models.TypeclassBase(name, bases, attrs)[source]

Bases: SharedMemoryModelBase

Metaclass which should be set for the root of model proxies that don’t define any new fields, like Object, Script etc. This is the basis for the typeclassing system.

evennia.typeclasses.models.call_at_first_save(sender, instance, created, **kwargs)[source]

Receives a signal just after the object is saved.

evennia.typeclasses.models.class_from_module(path, defaultpaths=None, fallback=None)[source]

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.typeclasses.models.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 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.typeclasses.models.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.

class evennia.typeclasses.models.lazy_property(func: Callable[[...], TProp], name=None, doc=None)[source]

Bases: Generic[TProp]

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: Callable[[...], TProp], name=None, doc=None)[source]

Store all properties for now

evennia.typeclasses.models.log_trace(msg=None, **kwargs)[source]

Log a traceback to the log. This should be called from within an exception.

Parameters:
  • msg (str, optional) – Adds an extra line with added info at the end of the traceback in the log.

  • **kwargs – If given, The msg is parsed as a format string with {..} formatting markers that should match the keywords.

evennia.typeclasses.models.remove_attributes_on_delete(sender, instance, **kwargs)[source]

Wipe object’s Attributes when it’s deleted

evennia.typeclasses.models.reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None, *, query=None, fragment=None)[source]
evennia.typeclasses.models.slugify(value, allow_unicode=False)[source]

Convert to ASCII if ‘allow_unicode’ is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren’t alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace, dashes, and underscores.

evennia.typeclasses.models.smart_str(s, encoding='utf-8', strings_only=False, errors='strict')[source]

Return a string representing ‘s’. Treat bytestrings using the ‘encoding’ codec.

If strings_only is True, don’t convert (some) non-string-like objects.