Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set part of a lambda function in advance to avoid repeated code

The following sorting method works perfectly.

def sort_view_items(self):

    cs = self.settings.case_sensitive

    if self.settings.sort_by_file_name:
        sk = lambda vi: (vi.name if cs else vi.name.lower(), vi.group, vi.tab)

    elif self.settings.sort_by_folder:
        sk = lambda vi: (vi.folder, vi.name if cs else vi.name.lower())

    elif self.settings.sort_by_syntax:
        sk = lambda vi: (vi.syntax, vi.name if cs else vi.name.lower())

    elif self.settings.sort_by_indexes:
        sk = lambda vi: (vi.group, vi.tab)

    self.view_items.sort(key = sk)

However the case sensitive related section of the lambdas vi.name if cs else vi.name.lower() gets used 3 times which irks my repeated code gene.

Out of interest, can the case aspect be set in advance somehow, but without making permenant changes to the name attribute or doing so in a temporary copy of the view_items list?

For example I tried using a lambda within a lambda which I didn't think would work and, guess what, it didn't. Although unexpectedly the syntax was accepted (no exceptions), it just didn't result in any sorting being actually performed.

def sort_view_items(self):

    cs = self.settings.case_sensitive

    name_lambda = lambda vi: vi.name if cs else vi.name.lower()

    if self.settings.sort_by_file_name:
        sk = lambda vi: (name_lambda, vi.group, vi.tab)

    ...
like image 914
mattst Avatar asked Aug 07 '16 14:08

mattst


1 Answers

You need to actually call name_lambda:

sk = lambda vi: (name_lambda(vi), vi.group, vi.tab)

In your snippet, name_lambda is defined correctly but it is never going to be called.

like image 152
flornquake Avatar answered Oct 05 '22 23:10

flornquake