Add "AdvancedList" to collections

from collections import namedtuple

User = namedtuple('User', ['id', 'name'])

class AdvancedList(list):

    def get(self, attr: str) -> list:
        return [getattr(i, attr) for i in self]

    def map(self, key: str) -> dict:
        return {getattr(i, key): i for i in self}

if __name__ == '__main__':
    advanced_list = AdvancedList([User(1, 'Bob'), User(2, 'Alice')])
    user_ids = advanced_list.get('id')
    output: [1, 2]
    id_user_mapping ='id')
    output: {1: User(id=1, name='Bob'), 2: User(id=2, name='Alice')}

I think it’s really helpful to have an “AdvanedList” in collections
Maybe it seems so easy but really help, because we write a lot of comprehensions to get an attibutes list or an attribute object mapping :laughing:

I don’t think this is a common use case at all (and this name doesn’t tell me anything about what the class does or why I’d want it). If you commonly find yourself transforming input data in this way, consider putting more effort into the code that created the input data in the first place.

This doesn’t even save typing - consider that the example code steps,

x = AdvancedList([User(1, 'Bob'), User(2, 'Alice')])
y = x.get('id')
z ='id')

are replacing code that doesn’t need to make the wrapper in the first place:

x = [User(1, 'Bob'), User(2, 'Alice')]
y = [ for i in x]
z = { for i in x}

That’s 6 or 8 extra characters per invocation (8 or 10, assuming that the real identifier name for “x” is, on average, as long as the real name for the convenience method in the actual implementation), vs. the need to use the wrapper (which will also be slower in cases where the attribute name is static).

get() on a list intrigued me, but this implementation has a lot of overlap with dict, which has .get() and is already a mapping. I guess I’d need some other real world examples to understand its use case.

Hello Karl, thanks for your reply.I am really sorry about the class name I don’t know how to call it yet, thus I just call it “AdvancedList”.But I think it’s very common in ORM batch query situation.For example firstly you query a batch of users(a list of User object not just id column) from the User table by other columns(age, gender, or something else) then you wanna query another table(UserComment) which has the user_id column.As this time you really nead a user_id list to batch query UserComment.After query UserComment you need to replace comment’s user_id with user object to form a list of user’scomment (Maybe joining two tables will be easier).

Hi, py. As far as I am concerned,there is a case in ORM batch query, you need to get a list of attribute of a list object to query objects of another table.

You can easily get a list of attribute or a attribute object mapping of objects just by a function call not comprehension