changeset 8270:5725fa4cfecd

cleanup: minimize use of lambda expressions - we have 'def' for that purpose Fix some flake8 warnings "E731 do not assign a lambda expression, use a def".
author Mads Kiilerich <mads@kiilerich.com>
date Sun, 04 Aug 2019 00:07:10 +0200
parents e1d4a0d8520f
children 2ce0bc6e85f1
files kallithea/controllers/admin/repo_groups.py kallithea/controllers/admin/user_groups.py kallithea/controllers/admin/users.py kallithea/lib/auth_modules/auth_ldap.py kallithea/lib/celerylib/tasks.py kallithea/lib/helpers.py kallithea/lib/rcmail/response.py kallithea/lib/vcs/backends/git/changeset.py kallithea/lib/vcs/backends/git/repository.py kallithea/lib/vcs/conf/settings.py kallithea/lib/vcs/utils/paths.py kallithea/model/repo.py kallithea/model/validators.py setup.py
diffstat 14 files changed, 71 insertions(+), 70 deletions(-) [+]
line wrap: on
line diff
--- a/kallithea/controllers/admin/repo_groups.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/controllers/admin/repo_groups.py	Sun Aug 04 00:07:10 2019 +0200
@@ -104,15 +104,14 @@
         _tmpl_lookup = app_globals.mako_lookup
         template = _tmpl_lookup.get_template('data_table/_dt_elements.html')
 
-        repo_group_name = lambda repo_group_name, children_groups: (
-            template.get_def("repo_group_name")
-            .render_unicode(repo_group_name, children_groups, _=_, h=h, c=c)
-        )
-        repo_group_actions = lambda repo_group_id, repo_group_name, gr_count: (
-            template.get_def("repo_group_actions")
-            .render_unicode(repo_group_id, repo_group_name, gr_count, _=_, h=h, c=c,
-                    ungettext=ungettext)
-        )
+        def repo_group_name(repo_group_name, children_groups):
+            return template.get_def("repo_group_name") \
+                .render_unicode(repo_group_name, children_groups, _=_, h=h, c=c)
+
+        def repo_group_actions(repo_group_id, repo_group_name, gr_count):
+            return template.get_def("repo_group_actions") \
+                .render_unicode(repo_group_id, repo_group_name, gr_count, _=_, h=h, c=c,
+                        ungettext=ungettext)
 
         for repo_gr in group_iter:
             children_groups = [g.name for g in repo_gr.parents] + [repo_gr.name]
--- a/kallithea/controllers/admin/user_groups.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/controllers/admin/user_groups.py	Sun Aug 04 00:07:10 2019 +0200
@@ -89,16 +89,15 @@
         _tmpl_lookup = app_globals.mako_lookup
         template = _tmpl_lookup.get_template('data_table/_dt_elements.html')
 
-        user_group_name = lambda user_group_id, user_group_name: (
-            template.get_def("user_group_name")
-            .render_unicode(user_group_id, user_group_name, _=_, h=h, c=c)
-        )
-        user_group_actions = lambda user_group_id, user_group_name: (
-            template.get_def("user_group_actions")
-            .render_unicode(user_group_id, user_group_name, _=_, h=h, c=c)
-        )
+        def user_group_name(user_group_id, user_group_name):
+            return template.get_def("user_group_name") \
+                .render_unicode(user_group_id, user_group_name, _=_, h=h, c=c)
+
+        def user_group_actions(user_group_id, user_group_name):
+            return template.get_def("user_group_actions") \
+                .render_unicode(user_group_id, user_group_name, _=_, h=h, c=c)
+
         for user_gr in group_iter:
-
             user_groups_data.append({
                 "raw_name": user_gr.users_group_name,
                 "group_name": user_group_name(user_gr.users_group_id,
--- a/kallithea/controllers/admin/users.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/controllers/admin/users.py	Sun Aug 04 00:07:10 2019 +0200
@@ -75,13 +75,13 @@
 
         grav_tmpl = '<div class="gravatar">%s</div>'
 
-        username = lambda user_id, username: (
-                template.get_def("user_name")
-                .render_unicode(user_id, username, _=_, h=h, c=c))
+        def username(user_id, username):
+            return template.get_def("user_name") \
+                .render_unicode(user_id, username, _=_, h=h, c=c)
 
-        user_actions = lambda user_id, username: (
-                template.get_def("user_actions")
-                .render_unicode(user_id, username, _=_, h=h, c=c))
+        def user_actions(user_id, username):
+            return template.get_def("user_actions") \
+                .render_unicode(user_id, username, _=_, h=h, c=c)
 
         for user in c.users_list:
             users_data.append({
--- a/kallithea/lib/auth_modules/auth_ldap.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/lib/auth_modules/auth_ldap.py	Sun Aug 04 00:07:10 2019 +0200
@@ -327,7 +327,8 @@
             (user_dn, ldap_attrs) = aldap.authenticate_ldap(username, password)
             log.debug('Got ldap DN response %s', user_dn)
 
-            get_ldap_attr = lambda k: ldap_attrs.get(settings.get(k), [''])[0]
+            def get_ldap_attr(k):
+                return ldap_attrs.get(settings.get(k), [''])[0]
 
             # old attrs fetched from Kallithea database
             admin = getattr(userobj, 'admin', False)
--- a/kallithea/lib/celerylib/tasks.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/lib/celerylib/tasks.py	Sun Aug 04 00:07:10 2019 +0200
@@ -66,6 +66,11 @@
                          .run(full_index=full_index)
 
 
+# for js data compatibility cleans the key for person from '
+def akc(k):
+    return person(k).replace('"', '')
+
+
 @celerylib.task
 @celerylib.dbsession
 def get_commits_stats(repo_name, ts_min_y, ts_max_y, recurse_limit=100):
@@ -79,9 +84,6 @@
     try:
         lock = celerylib.DaemonLock(os.path.join(lockkey_path, lockkey))
 
-        # for js data compatibility cleans the key for person from '
-        akc = lambda k: person(k).replace('"', "")
-
         co_day_auth_aggr = {}
         commits_by_day_aggregate = {}
         repo = Repository.get_by_repo_name(repo_name)
--- a/kallithea/lib/helpers.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/lib/helpers.py	Sun Aug 04 00:07:10 2019 +0200
@@ -502,11 +502,19 @@
     return [_Message(category, message) for category, message in _session_flash_messages(clear=True)]
 
 
-age = lambda x, y=False: _age(x, y)
-capitalize = lambda x: x.capitalize()
+def age(x, y=False):
+    return _age(x, y)
+
+def capitalize(x):
+    return x.capitalize()
+
 email = author_email
-short_id = lambda x: x[:12]
-hide_credentials = lambda x: ''.join(credentials_filter(x))
+
+def short_id(x):
+    return x[:12]
+
+def hide_credentials(x):
+    return ''.join(credentials_filter(x))
 
 
 def show_id(cs):
@@ -602,15 +610,12 @@
 
 def person_by_id(id_, show_attr="username"):
     from kallithea.model.db import User
-    # attr to return from fetched user
-    person_getter = lambda usr: getattr(usr, show_attr)
-
     # maybe it's an ID ?
     if str(id_).isdigit() or isinstance(id_, int):
         id_ = int(id_)
         user = User.get(id_)
         if user is not None:
-            return person_getter(user)
+            return getattr(user, show_attr)
     return id_
 
 
@@ -862,10 +867,7 @@
             .replace('[', '<b>') \
             .replace(']', '</b>')
 
-    action_params_func = lambda: ""
-
-    if callable(action_str[1]):
-        action_params_func = action_str[1]
+    action_params_func = action_str[1] if callable(action_str[1]) else (lambda: "")
 
     def action_parser_icon():
         action = user_log.action
@@ -1176,7 +1178,8 @@
         assert CONFIG['sqlalchemy.url'] # make sure config has been loaded
 
         # Build chain of urlify functions, starting with not doing any transformation
-        tmp_urlify_issues_f = lambda s: s
+        def tmp_urlify_issues_f(s):
+            return s
 
         issue_pat_re = re.compile(r'issue_pat(.*)')
         for k in CONFIG:
@@ -1228,9 +1231,9 @@
                      'url': issue_url,
                      'text': issue_text,
                     }
-            tmp_urlify_issues_f = (lambda s,
-                                          issue_re=issue_re, issues_replace=issues_replace, chain_f=tmp_urlify_issues_f:
-                                   issue_re.sub(issues_replace, chain_f(s)))
+
+            def tmp_urlify_issues_f(s, issue_re=issue_re, issues_replace=issues_replace, chain_f=tmp_urlify_issues_f):
+                return issue_re.sub(issues_replace, chain_f(s))
 
         # Set tmp function globally - atomically
         _urlify_issues_f = tmp_urlify_issues_f
--- a/kallithea/lib/rcmail/response.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/lib/rcmail/response.py	Sun Aug 04 00:07:10 2019 +0200
@@ -44,7 +44,9 @@
 
 ADDRESS_HEADERS_WHITELIST = ['From', 'To', 'Delivered-To', 'Cc']
 DEFAULT_ENCODING = "utf-8"
-VALUE_IS_EMAIL_ADDRESS = lambda v: '@' in v
+
+def VALUE_IS_EMAIL_ADDRESS(v):
+    return '@' in v
 
 
 def normalize_header(header):
--- a/kallithea/lib/vcs/backends/git/changeset.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/lib/vcs/backends/git/changeset.py	Sun Aug 04 00:07:10 2019 +0200
@@ -435,8 +435,8 @@
                 raise NodeDoesNotExistError("Cannot find one of parents' "
                     "directories for a given path: %s" % path)
 
-            _GL = lambda m: m and objects.S_ISGITLINK(m)
-            if _GL(self._stat_modes.get(path)):
+            stat = self._stat_modes.get(path)
+            if stat and objects.S_ISGITLINK(stat):
                 tree = self.repository._repo[self._tree_id]
                 cf = ConfigFile.from_file(BytesIO(self.repository._repo.get_object(tree[b'.gitmodules'][1]).data))
                 url = ascii_str(cf.get(('submodule', path), 'url'))
--- a/kallithea/lib/vcs/backends/git/repository.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/lib/vcs/backends/git/repository.py	Sun Aug 04 00:07:10 2019 +0200
@@ -358,10 +358,9 @@
     def branches(self):
         if not self.revisions:
             return {}
-        sortkey = lambda ctx: ctx[0]
         _branches = [(safe_str(key), ascii_str(sha))
                      for key, (sha, type_) in self._parsed_refs.items() if type_ == b'H']
-        return OrderedDict(sorted(_branches, key=sortkey, reverse=False))
+        return OrderedDict(sorted(_branches, key=(lambda ctx: ctx[0]), reverse=False))
 
     @LazyProperty
     def closed_branches(self):
@@ -374,11 +373,9 @@
     def _get_tags(self):
         if not self.revisions:
             return {}
-
-        sortkey = lambda ctx: ctx[0]
         _tags = [(safe_str(key), ascii_str(sha))
                  for key, (sha, type_) in self._parsed_refs.items() if type_ == b'T']
-        return OrderedDict(sorted(_tags, key=sortkey, reverse=True))
+        return OrderedDict(sorted(_tags, key=(lambda ctx: ctx[0]), reverse=True))
 
     def tag(self, name, user, revision=None, message=None, date=None,
             **kwargs):
--- a/kallithea/lib/vcs/conf/settings.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/lib/vcs/conf/settings.py	Sun Aug 04 00:07:10 2019 +0200
@@ -5,7 +5,8 @@
 from kallithea.lib.vcs.utils.paths import get_user_home
 
 
-abspath = lambda * p: os.path.abspath(os.path.join(*p))
+def abspath(*p):
+    return os.path.abspath(os.path.join(*p))
 
 VCSRC_PATH = os.environ.get('VCSRC_PATH')
 
--- a/kallithea/lib/vcs/utils/paths.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/lib/vcs/utils/paths.py	Sun Aug 04 00:07:10 2019 +0200
@@ -1,7 +1,8 @@
 import os
 
 
-abspath = lambda * p: os.path.abspath(os.path.join(*p))
+def abspath(*p):
+    return os.path.abspath(os.path.join(*p))
 
 
 def get_dirs_for_path(*paths):
--- a/kallithea/model/repo.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/model/repo.py	Sun Aug 04 00:07:10 2019 +0200
@@ -109,12 +109,11 @@
         :param user:
         """
         from kallithea.lib.auth import AuthUser
-        user = User.guess_instance(user)
-        repos = AuthUser(dbuser=user).permissions['repositories']
-        access_check = lambda r: r[1] in ['repository.read',
-                                          'repository.write',
-                                          'repository.admin']
-        repos = [x[0] for x in filter(access_check, repos.items())]
+        auth_user = AuthUser(dbuser=User.guess_instance(user))
+        repos = [repo_name
+            for repo_name, perm in auth_user.permissions['repositories'].items()
+            if perm in ['repository.read', 'repository.write', 'repository.admin']
+            ]
         return Repository.query().filter(Repository.repo_name.in_(repos))
 
     @classmethod
--- a/kallithea/model/validators.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/kallithea/model/validators.py	Sun Aug 04 00:07:10 2019 +0200
@@ -186,11 +186,7 @@
             slug = repo_name_slug(group_name)
 
             # check for parent of self
-            parent_of_self = lambda: (
-                old_data['group_id'] == parent_group_id
-                if parent_group_id else False
-            )
-            if edit and parent_of_self():
+            if edit and parent_group_id and old_data['group_id'] == parent_group_id:
                 msg = self.message('parent_group_id', state)
                 raise formencode.Invalid(msg, value, state,
                     error_dict=dict(parent_group_id=msg)
--- a/setup.py	Thu Feb 13 14:46:50 2020 +0100
+++ b/setup.py	Sun Aug 04 00:07:10 2019 +0200
@@ -20,16 +20,17 @@
     import re
     matches = re.compile(r'(?:%s)\s*=\s*(.*)' % name).search(data)
     if matches:
-        if not callable(callback_handler):
-            callback_handler = lambda v: v
-
-        return callback_handler(eval(matches.groups()[0]))
+        s = eval(matches.groups()[0])
+        if callable(callback_handler):
+            return callback_handler(s)
+        return s
 
 _meta = open(os.path.join(here, 'kallithea', '__init__.py'), 'r')
 _metadata = _meta.read()
 _meta.close()
 
-callback = lambda V: ('.'.join(map(str, V[:3])) + '.'.join(V[3:]))
+def callback(V):
+    return '.'.join(map(str, V[:3])) + '.'.join(V[3:])
 __version__ = _get_meta_var('VERSION', _metadata, callback)
 __license__ = _get_meta_var('__license__', _metadata)
 __author__ = _get_meta_var('__author__', _metadata)