aboutsummaryrefslogtreecommitdiff
path: root/discord/utils.py
diff options
context:
space:
mode:
authorRapptz <[email protected]>2015-09-13 22:28:02 -0400
committerRapptz <[email protected]>2015-09-13 22:28:02 -0400
commitf59ab28741081ee712afb7b6bf79d18df79aa1bd (patch)
tree7427e00fc3cda46408e842a5dfdcaaf50181c88a /discord/utils.py
parentAdd get_default_role for servers to get the 'everyone' role. (diff)
downloaddiscord.py-f59ab28741081ee712afb7b6bf79d18df79aa1bd.tar.xz
discord.py-f59ab28741081ee712afb7b6bf79d18df79aa1bd.zip
Add utils.find helper function.
Diffstat (limited to 'discord/utils.py')
-rw-r--r--discord/utils.py23
1 files changed, 23 insertions, 0 deletions
diff --git a/discord/utils.py b/discord/utils.py
index 0db28091..8e328bfa 100644
--- a/discord/utils.py
+++ b/discord/utils.py
@@ -32,3 +32,26 @@ def parse_time(timestamp):
if timestamp:
return datetime.datetime(*map(int, re_split(r'[^\d]', timestamp.replace('+00:00', ''))))
return None
+
+def find(predicate, seq):
+ """A helper to return the first element found in the sequence
+ that meets the predicate. For example: ::
+
+ member = find(lambda m: m.name == 'Mighty', channel.server.members)
+
+ would find the first :class:`Member` whose name is 'Mighty' and return it.
+
+ This is different from `filter`_ due to the fact it stops the moment it finds
+ a valid entry.
+
+ .. _filter: https://docs.python.org/3.6/library/functions.html#filter
+
+ :param predicate: A function that returns a boolean-like result.
+ :param seq: The sequence to iterate through.
+ :return: The first result of the predicate that returned a ``True``-like value or ``None`` if nothing was found.
+ """
+
+ for element in seq:
+ if predicate(element):
+ return element
+ return None