Browse Source

Add more special methods to Namespace for ease of use.

* __getattr__ would allow it to no longer AttributeError while
  simultaneously letting linters and type checkers understand that
  this is a bag of dynamic attributes.
* __contains__ allows checking for the existence of an attribute
* __getitem__ allows accessing a value even if its name is not a valid
  Python identifier.
pull/7692/head
Rapptz 3 years ago
parent
commit
aa006f345a
  1. 19
      discord/app_commands/namespace.py

19
discord/app_commands/namespace.py

@ -68,7 +68,8 @@ class Namespace:
This class is deliberately simple and just holds the option name and resolved value as a simple This class is deliberately simple and just holds the option name and resolved value as a simple
key-pair mapping. These attributes can be accessed using dot notation. For example, an option key-pair mapping. These attributes can be accessed using dot notation. For example, an option
with the name of ``example`` can be accessed using ``ns.example``. with the name of ``example`` can be accessed using ``ns.example``. If an attribute is not found,
then ``None`` is returned rather than an attribute error.
.. versionadded:: 2.0 .. versionadded:: 2.0
@ -80,6 +81,13 @@ class Namespace:
.. describe:: x != y .. describe:: x != y
Checks if two namespaces are not equal. Checks if two namespaces are not equal.
.. describe:: x[key]
Returns an attribute if it is found, otherwise raises
a :exc:`KeyError`.
.. describe:: key in x
Checks if the attribute is in the namespace.
This namespace object converts resolved objects into their appropriate form depending on their This namespace object converts resolved objects into their appropriate form depending on their
type. Consult the table below for conversion information. type. Consult the table below for conversion information.
@ -213,6 +221,15 @@ class Namespace:
return self.__dict__ == other.__dict__ return self.__dict__ == other.__dict__
return NotImplemented return NotImplemented
def __getitem__(self, key: str) -> Any:
return self.__dict__[key]
def __contains__(self, key: str) -> Any:
return key in self.__dict__
def __getattr__(self, attr: str) -> Any:
return None
def _update_with_defaults(self, defaults: Iterable[Tuple[str, Any]]) -> None: def _update_with_defaults(self, defaults: Iterable[Tuple[str, Any]]) -> None:
for key, value in defaults: for key, value in defaults:
self.__dict__.setdefault(key, value) self.__dict__.setdefault(key, value)

Loading…
Cancel
Save