utils.get now supports nested attribute retrieval.

This commit is contained in:
Rapptz 2015-12-30 13:00:52 -05:00
parent f1480580c1
commit 7765580a14

View File

@ -88,6 +88,9 @@ def get(iterable, **attrs):
logical AND, not logical OR. Meaning they have to meet every logical AND, not logical OR. Meaning they have to meet every
attribute passed in and not one of them. attribute passed in and not one of them.
To have a nested attribute search (i.e. search by ``x.y``) then
pass in ``x__y`` as the keyword argument.
If nothing is found that matches the attributes passed, then If nothing is found that matches the attributes passed, then
``None`` is returned. ``None`` is returned.
@ -106,6 +109,12 @@ def get(iterable, **attrs):
channel = discord.utils.get(server.channels, name='Foo', type=ChannelType.voice) channel = discord.utils.get(server.channels, name='Foo', type=ChannelType.voice)
Nested attribute matching:
.. code-block:: python
channel = discord.utils.get(client.get_all_channels(), server__name='Cool', name='general')
Parameters Parameters
----------- -----------
iterable iterable
@ -116,9 +125,12 @@ def get(iterable, **attrs):
def predicate(elem): def predicate(elem):
for attr, val in attrs.items(): for attr, val in attrs.items():
if not hasattr(elem, attr): nested = attr.split('__')
return False obj = elem
if getattr(elem, attr) != val: for attribute in nested:
obj = getattr(obj, attribute)
if obj != val:
return False return False
return True return True