diff options
| author | Rapptz <[email protected]> | 2015-12-13 01:56:24 -0500 |
|---|---|---|
| committer | Rapptz <[email protected]> | 2015-12-13 02:13:08 -0500 |
| commit | 338fb3e504b69f6fa0eaa993b1da6001e1742fab (patch) | |
| tree | 3494c8eb90daf202939025ad0a264c2895f31dfe | |
| parent | Implement cache of login credentials. (diff) | |
| download | discord.py-338fb3e504b69f6fa0eaa993b1da6001e1742fab.tar.xz discord.py-338fb3e504b69f6fa0eaa993b1da6001e1742fab.zip | |
Add discord.utils.get helper.
| -rw-r--r-- | discord/utils.py | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/discord/utils.py b/discord/utils.py index 97584b31..2662b4a1 100644 --- a/discord/utils.py +++ b/discord/utils.py @@ -59,6 +59,52 @@ def find(predicate, seq): return element return None +def get(iterable, **attrs): + """A helper that returns the first element in the iterable that meets + all the traits passed in ``attrs``. This is an alternative for + :func:`discord.utils.find`. + + When multiple attributes are specified, they are checked using + logical AND, not logical OR. Meaning they have to meet every + attribute passed in and not one of them. + + If nothing is found that matches the attributes passed, then + ``None`` is returned. + + Examples + --------- + + Basic usage: + + .. code-block:: python + + member = discord.utils.get(message.server.members, name='Foo') + + Multiple attribute matching: + + .. code-block:: python + + channel = discord.utils.get(server.channels, name='Foo', type=ChannelType.voice) + + Parameters + ----------- + iterable + An iterable to search through. + **attrs + Keyword arguments that denote attributes to search with. + """ + + def predicate(elem): + for attr, val in attrs.items(): + if not hasattr(elem, attr): + return False + if getattr(elem, attr) != val: + return False + return True + + return find(predicate, iterable) + + def _null_event(*args, **kwargs): pass |