Skip to content

Commit

Permalink
Add DataStore.get_as
Browse files Browse the repository at this point in the history
  • Loading branch information
tandemdude committed Jul 16, 2022
1 parent f5e7e98 commit b057cb1
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
5 changes: 5 additions & 0 deletions docs/source/changelogs/v2-changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ Below are all the changelogs for the stable versions of hikari-lightbulb (versio

----

Version 2.2.4
=============

- Add :obj:`~lightbulb.utils.data_store.DataStore.get_as` to allow ``DataStore`` to be more type-complete.

Version 2.2.3
=============

Expand Down
2 changes: 1 addition & 1 deletion lightbulb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,4 @@
from lightbulb.help_command import *
from lightbulb.plugins import *

__version__ = "2.2.3"
__version__ = "2.2.4"
22 changes: 21 additions & 1 deletion lightbulb/utils/data_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@

import typing as t

T = t.TypeVar("T")


class DataStore(t.Dict[str, t.Any]):
"""
Data storage class allowing setting, retrieval and unsetting of custom
attributes. This class subclasses dict so the data can be accessed the same
attributes. This class subclasses :obj:`dict` so the data can be accessed the same
as you would a dictionary as well as using dot notation.
Example:
Expand Down Expand Up @@ -57,3 +59,21 @@ def __setattr__(self, key: str, value: t.Any) -> None:

def __delattr__(self, item: str) -> None:
self.pop(item, None)

def get_as(self, item: str, type: t.Type[T]) -> T:
"""
Helper method to allow type-complete getting of items from this ``DataStore``.
Args:
item (:obj:`str`): The name of the key that the item is stored at.
type (Type[T]): The type to cast the item as.
Returns:
T: The item stored at key ``item``, cast to the given type.
Raises:
:obj:`ValueError`: If a key of name ``item`` has not been set.
"""
if item not in self:
raise TypeError(f"Item {item!r} was never set")
return t.cast(type, self.get(item)) # type: ignore

0 comments on commit b057cb1

Please sign in to comment.