Source code for nbtparse.minecraft.entity_ids
import collections
import collections.abc as cabc
import logging
import types
import weakref
from .. import exceptions
logger = logging.getLogger(__name__)
_REGISTERED_CLASSES = collections.defaultdict(weakref.WeakValueDictionary)
# Keys: module name (string)
# Values: dictionaries mapping identifier strings to classes
[docs]class Namespace(cabc.Mapping):
"""Immutable namespace of entities.
Maps identifier strings to classes. Temporary classes are kept alive by
being in the mapping.
"""
def __init__(self, *args, **kwargs):
self._mapping = dict(*args, **kwargs)
def __repr__(self):
return ('<Namespace (entity_ids): {!r} entries>'
.format(len(self)))
def __getitem__(self, key):
return self._mapping[key]
def __iter__(self):
return iter(self._mapping)
def __len__(self):
return len(self._mapping)
[docs]def register_class(ident: str) -> callable:
"""Decorator to register a class with the entity IDs system.
Usually called automatically from :class:`entity.EntityMeta`; you should
not need to call this yourself.
"""
def decorator(class_: 'entity.EntityMeta') -> 'entity.EntityMeta':
module_name = class_.__module__
_REGISTERED_CLASSES[module_name][ident] = class_
return class_
return decorator
[docs]def make_namespace(*modules: types.ModuleType) -> Namespace:
"""Return a :class:`Namespace` created from the given modules.
All classes which have been declared at the top level or decorated with
:func:`register_class` are included in the namespace.
"""
registered_names = {}
for module in modules:
registered_names.update(_REGISTERED_CLASSES[module.__name__])
return Namespace(registered_names)
_VANILLA = {}
VANILLA = None
"""The :class:`Namespace` containing all vanilla entities."""
def _make_vanilla(*modules: types.ModuleType) -> None:
global VANILLA
VANILLA = make_namespace(*modules)