0

I got some little code snippet and i think about refactoring. I really don't like it in part of sort_paths_by_date method beacuse of DRY principle and code clarity:

from os.path import getctime, getmtime

class Endpoint(object):
    def __init__(self, define_path_by, paths):
        self.define_path_by = define_path_by
        self.paths = paths

    def sort_paths_by_date(self):
        if self.define_path_by == 'ctime':
            self.paths = sorted(
                self.paths,
                key=lambda cur_path: getctime(cur_path.path),
            )
        elif self.define_path_by == 'mtime':
            self.paths = sorted(
                self.paths,
                key=lambda cur_path: getmtime(cur_path.path),
            )

and i make it like this:

from os.path import getctime, getmtime

class Endpoint(object):
    def __init__(self, define_path_by, paths):
        self.define_path_by = define_path_by
        self.paths = paths

    def sort_paths_by_date(self):
        def sort_with_func(func):
            return sorted(
                self.paths, 
                key=lambda cur_path: func(cur_path.path)
            )

        if self.define_date_by == 'ctime':
            self.paths = sort_with_func(getctime)
        elif self.define_date_by == 'mtime':
            self.paths = sort_with_func(getmtime)

But now i'm not sure about function definition in method and again code clarity is confused me. So i will be appreciative for your refactoring experience here.

1 Answer 1

2

Your function does seem a little unnecessarily complicated. It could simply be this:

def sort_paths_by_date(self):
    if self.define_path_by in ('ctime', 'mtime'):
        fn = getctime if self.define_path='ctime' else getmtime
        self.paths = sorted(self.paths, key=lambda cur_path: fn(cur_path.path))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.