From 99fb6d8a905f01c37aa0651ba7e6bfcdb4d6398a Mon Sep 17 00:00:00 2001
From: Cyril Jouve <jv.cyril@gmail.com>
Date: Fri, 28 Aug 2020 18:52:24 +0200
Subject: [PATCH 3/7] several transformations that make Python code more
 idiomatic

---
 tools/sql_keywords.py                         |  2 +-
 web/pgadmin/__init__.py                       |  2 +-
 web/pgadmin/authenticate/ldap.py              |  2 +-
 .../browser/server_groups/servers/__init__.py |  4 +-
 .../databases/external_tables/__init__.py     |  6 +--
 .../external_tables/mapping_utils.py          |  3 +-
 .../external_tables/tests/test_properties.py  |  2 +-
 .../schemas/foreign_tables/__init__.py        |  2 +-
 .../schemas/tables/schema_diff_utils.py       |  6 +--
 .../server_groups/servers/roles/__init__.py   |  8 +--
 web/pgadmin/browser/tests/test_ldap_login.py  | 52 ++++++++-----------
 .../tools/backup/tests/test_backup_utils.py   |  4 +-
 .../tests/test_create_maintenance_job.py      |  4 +-
 .../restore/tests/test_create_restore_job.py  |  4 +-
 .../tools/schema_diff/directory_compare.py    | 40 +++++++-------
 web/pgadmin/tools/sqleditor/__init__.py       |  6 +--
 web/pgadmin/tools/sqleditor/command.py        |  4 +-
 .../sqleditor/utils/start_running_query.py    |  2 +-
 web/pgadmin/utils/ajax.py                     |  2 +-
 web/pgadmin/utils/csv.py                      |  2 +-
 web/pgadmin/utils/driver/psycopg2/__init__.py |  2 +-
 .../utils/driver/psycopg2/connection.py       |  6 +--
 web/pgadmin/utils/driver/psycopg2/cursor.py   |  2 +-
 web/pgadmin/utils/preferences.py              |  8 +--
 .../python_test_utils/test_utils.py           |  2 +-
 web/regression/re_sql/tests/test_resql.py     |  2 +-
 26 files changed, 85 insertions(+), 94 deletions(-)

diff --git a/tools/sql_keywords.py b/tools/sql_keywords.py
index 6d4c6f1e3..a862dcbbc 100644
--- a/tools/sql_keywords.py
+++ b/tools/sql_keywords.py
@@ -49,7 +49,7 @@ def get_release_tag(current_url=PG_CURRENT_VERSION_URL,
                     version_regex=PG_CURRENT_VERSION_REGEX):
     resp_text = get_file_from_url(current_url)
     version = apply_regex(resp_text, version_regex)
-    if type(version) == list:
+    if isinstance(version, list):
         version = version[0]
 
     return "REL_" + version.replace(".", "_")
diff --git a/web/pgadmin/__init__.py b/web/pgadmin/__init__.py
index e3ec4b57e..4bb58fcd1 100644
--- a/web/pgadmin/__init__.py
+++ b/web/pgadmin/__init__.py
@@ -164,7 +164,7 @@ class PgAdmin(Flask):
 
     def register_logout_hook(self, module):
         if hasattr(module, 'on_logout') and \
-                type(getattr(module, 'on_logout')) == MethodType:
+                isinstance(getattr(module, 'on_logout'), MethodType):
             self.logout_hooks.append(module)
 
 
diff --git a/web/pgadmin/authenticate/ldap.py b/web/pgadmin/authenticate/ldap.py
index 208ac6739..2cdca8605 100644
--- a/web/pgadmin/authenticate/ldap.py
+++ b/web/pgadmin/authenticate/ldap.py
@@ -189,7 +189,7 @@ class LDAPAuthentication(BaseAuthentication):
         # Create the TLS configuration object if required
         tls = None
 
-        if type(uri) == str:
+        if isinstance(uri, str):
             return False, "LDAP configuration error: Set the proper LDAP URI."
 
         if uri.scheme == 'ldaps' or config.LDAP_USE_STARTTLS:
diff --git a/web/pgadmin/browser/server_groups/servers/__init__.py b/web/pgadmin/browser/server_groups/servers/__init__.py
index 18e7a55c1..566273e57 100644
--- a/web/pgadmin/browser/server_groups/servers/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/__init__.py
@@ -38,10 +38,10 @@ def has_any(data, keys):
     """
     Checks any one of the keys present in the data given
     """
-    if data is None and type(data) != dict:
+    if data is None and not isinstance(data, dict):
         return False
 
-    if keys is None and type(keys) != list:
+    if keys is None and not isinstance(keys, list):
         return False
 
     for key in keys:
diff --git a/web/pgadmin/browser/server_groups/servers/databases/external_tables/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/external_tables/__init__.py
index 8c256bb26..cf902321e 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/external_tables/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/external_tables/__init__.py
@@ -167,7 +167,7 @@ class ExternalTablesView(PGChildNodeView):
 
         result = self.get_external_tables(database_id, sql_statement)
 
-        if type(result) is not list:
+        if not isinstance(result, list):
             return result
 
         return make_json_response(
@@ -197,10 +197,10 @@ class ExternalTablesView(PGChildNodeView):
         )
         result = self.get_external_tables(database_id, sql_statement)
 
-        if type(result) is not list:
+        if not isinstance(result, list):
             return result
 
-        if len(result) == 0:
+        if not result:
             return make_json_response(
                 data=gettext('Could not find the external table.'),
                 status=404
diff --git a/web/pgadmin/browser/server_groups/servers/databases/external_tables/mapping_utils.py b/web/pgadmin/browser/server_groups/servers/databases/external_tables/mapping_utils.py
index 53a472331..585eacc11 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/external_tables/mapping_utils.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/external_tables/mapping_utils.py
@@ -99,8 +99,7 @@ def format_options(format_type, options):
         return options
 
     result_options = tokenize_options(options)
-    all_keys = list(result_options.keys())
-    all_keys.sort()
+    all_keys = sorted(result_options)
     if format_type not in ['csv', 'text']:
         return ','.join([
             '%s = %s' % (key, result_options[key]) for key in all_keys
diff --git a/web/pgadmin/browser/server_groups/servers/databases/external_tables/tests/test_properties.py b/web/pgadmin/browser/server_groups/servers/databases/external_tables/tests/test_properties.py
index 9d292e3bb..742fb2167 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/external_tables/tests/test_properties.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/external_tables/tests/test_properties.py
@@ -130,7 +130,7 @@ class TestProperties(BaseTestGenerator):
                 self.fail('No exception was raised')
         except PropertiesException as exception:
             if hasattr(self, 'expected_raise_exception'):
-                if type(exception) is self.expected_raise_exception:
+                if isinstance(exception, self.expected_raise_exception):
                     if hasattr(self,
                                'expected_internal_server_error_called_with'):
                         internal_server_error_mock.assert_called_with(
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/__init__.py b/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/__init__.py
index 766434e02..4686b5caf 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/foreign_tables/__init__.py
@@ -275,7 +275,7 @@ class ForeignTableView(PGChildNodeView, DataTypeReader,
                     ):
                         # Coverts string into python list as expected.
                         data[key] = []
-                        if type(req[key]) != list or len(req[key]) != 0:
+                        if not isinstance(req[key], list) and req[key]:
                             data[key] = json.loads(req[key], encoding='utf-8')
 
                         if key == 'inherits':
diff --git a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_utils.py b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_utils.py
index 2846a902b..c96f02937 100644
--- a/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_utils.py
+++ b/web/pgadmin/browser/server_groups/servers/databases/schemas/tables/schema_diff_utils.py
@@ -124,8 +124,7 @@ class SchemaDiffTableCompare(SchemaDiffObjectCompare):
 
         for source in source_cols:
             if 'name' in source:
-                if type(target_cols) is list and len(
-                        target_cols) > 0:
+                if isinstance(target_cols, list) and target_cols:
                     tmp = None
                     for item in target_cols:
                         if item['name'] == source['name']:
@@ -190,8 +189,7 @@ class SchemaDiffTableCompare(SchemaDiffObjectCompare):
             different[constraint] = {}
             for source in source_cols:
                 if 'name' in source:
-                    if type(target_cols) is list and len(
-                            target_cols) > 0:
+                    if isinstance(target_cols, list) and target_cols:
                         tmp_src = copy.deepcopy(source)
                         if 'oid' in tmp_src:
                             tmp_src.pop('oid')
diff --git a/web/pgadmin/browser/server_groups/servers/roles/__init__.py b/web/pgadmin/browser/server_groups/servers/roles/__init__.py
index c976ded38..e2f7aa935 100644
--- a/web/pgadmin/browser/server_groups/servers/roles/__init__.py
+++ b/web/pgadmin/browser/server_groups/servers/roles/__init__.py
@@ -119,11 +119,11 @@ class RoleView(PGChildNodeView):
         :param req_keys: required keys
         :return: Valid or Invalid
         """
-        if type(data) != list:
+        if not isinstance(data, list):
             return False
 
         for item in data:
-            if type(item) != dict:
+            if not isinstance(item, dict):
                 return False
 
             for a_key in req_keys:
@@ -142,7 +142,7 @@ class RoleView(PGChildNodeView):
         :param req_delete_keys: required keys when deleting
         :return: Valid or Invalid
         """
-        if type(data) != dict:
+        if not isinstance(data, dict):
             return False
 
         for op in [u'added', u'deleted', u'changed']:
@@ -188,7 +188,7 @@ class RoleView(PGChildNodeView):
 
             if data[u'rolconnlimit'] is not None:
                 data[u'rolconnlimit'] = int(data[u'rolconnlimit'])
-                if type(data[u'rolconnlimit']) != int or \
+                if not isinstance(data[u'rolconnlimit'], int) or \
                         data[u'rolconnlimit'] < -1:
                     return _("Connection limit must be an integer value "
                              "or equal to -1.")
diff --git a/web/pgadmin/browser/tests/test_ldap_login.py b/web/pgadmin/browser/tests/test_ldap_login.py
index e73e62e83..139d718ce 100644
--- a/web/pgadmin/browser/tests/test_ldap_login.py
+++ b/web/pgadmin/browser/tests/test_ldap_login.py
@@ -46,37 +46,31 @@ class LDAPLoginTestCase(BaseTestGenerator):
         cls.tester.logout()
 
     def setUp(self):
-        if 'ldap_config' in config_data and \
-                type(config_data['ldap_config']) is list and\
-                len(config_data['ldap_config']) > 0 and\
-                self.config_key_param in config_data['ldap_config'][0]:
+        try:
             ldap_config = config_data['ldap_config'][0][self.config_key_param]
+        except (KeyError, TypeError, IndexError):
+            self.skipTest("LDAP config not set.")
+        app_config.AUTHENTICATION_SOURCES = ['ldap']
+        app_config.LDAP_AUTO_CREATE_USER = True
+        app_config.LDAP_SERVER_URI = ldap_config['uri']
+        app_config.LDAP_BASE_DN = ldap_config['base_dn']
+        app_config.LDAP_USERNAME_ATTRIBUTE = ldap_config[
+            'username_atr']
+        app_config.LDAP_SEARCH_BASE_DN = ldap_config[
+            'search_base_dn']
+        app_config.LDAP_SEARCH_FILTER = ldap_config['search_filter']
+        app_config.LDAP_USE_STARTTLS = ldap_config['use_starttls']
+        app_config.LDAP_CA_CERT_FILE = ldap_config['ca_cert_file']
+        app_config.LDAP_CERT_FILE = ldap_config['cert_file']
+        app_config.LDAP_KEY_FILE = ldap_config['key_file']
+        if ldap_config['bind_user'] != "" and\
+                ldap_config['bind_password'] != "":
+            app_config.LDAP_BIND_USER = ldap_config['bind_user']
+            app_config.LDAP_BIND_PASSWORD = ldap_config['bind_password']
+        if ldap_config['anonymous_bind'] != "" and\
+                ldap_config['anonymous_bind']:
+            app_config.LDAP_ANONYMOUS_BIND = True
 
-            app_config.AUTHENTICATION_SOURCES = ['ldap']
-            app_config.LDAP_AUTO_CREATE_USER = True
-            app_config.LDAP_SERVER_URI = ldap_config['uri']
-            app_config.LDAP_BASE_DN = ldap_config['base_dn']
-            app_config.LDAP_USERNAME_ATTRIBUTE = ldap_config[
-                'username_atr']
-            app_config.LDAP_SEARCH_BASE_DN = ldap_config[
-                'search_base_dn']
-            app_config.LDAP_SEARCH_FILTER = ldap_config['search_filter']
-            app_config.LDAP_USE_STARTTLS = ldap_config['use_starttls']
-            app_config.LDAP_CA_CERT_FILE = ldap_config['ca_cert_file']
-            app_config.LDAP_CERT_FILE = ldap_config['cert_file']
-            app_config.LDAP_KEY_FILE = ldap_config['key_file']
-            if ldap_config['bind_user'] != "" and\
-                    ldap_config['bind_password'] != "":
-                app_config.LDAP_BIND_USER = ldap_config['bind_user']
-                app_config.LDAP_BIND_PASSWORD = ldap_config['bind_password']
-            if ldap_config['anonymous_bind'] != "" and\
-                    ldap_config['anonymous_bind']:
-                app_config.LDAP_ANONYMOUS_BIND = True
-
-        else:
-            self.skipTest(
-                "LDAP config not set."
-            )
 
     def runTest(self):
         """This function checks login functionality."""
diff --git a/web/pgadmin/tools/backup/tests/test_backup_utils.py b/web/pgadmin/tools/backup/tests/test_backup_utils.py
index eeddf4a1a..497a60e52 100644
--- a/web/pgadmin/tools/backup/tests/test_backup_utils.py
+++ b/web/pgadmin/tools/backup/tests/test_backup_utils.py
@@ -27,7 +27,7 @@ def run_backup_job(tester, job_id, expected_params, assert_in, assert_not_in,
                    assert_equal):
     cnt = 0
     the_process = None
-    while 1:
+    while True:
         if cnt >= 5:
             break
         # Check the process list
@@ -81,7 +81,7 @@ def run_backup_job(tester, job_id, expected_params, assert_in, assert_not_in,
 
     cnt = 0
     # Retrieve the backup job process logs
-    while 1:
+    while True:
         out, err, status = get_params(p_details_data)
         if status or cnt >= 5:
             break
diff --git a/web/pgadmin/tools/maintenance/tests/test_create_maintenance_job.py b/web/pgadmin/tools/maintenance/tests/test_create_maintenance_job.py
index e479ede34..c36fbd181 100644
--- a/web/pgadmin/tools/maintenance/tests/test_create_maintenance_job.py
+++ b/web/pgadmin/tools/maintenance/tests/test_create_maintenance_job.py
@@ -75,7 +75,7 @@ class MaintenanceJobTest(BaseTestGenerator):
 
         cnt = 0
         the_process = None
-        while 1:
+        while True:
             if cnt >= 10:
                 break
             # Check the process list
@@ -118,7 +118,7 @@ class MaintenanceJobTest(BaseTestGenerator):
         p_details_data = json.loads(p_details.data.decode('utf-8'))
 
         # Retrieve the backup job process logs
-        while 1:
+        while True:
             out, err, status = MaintenanceJobTest.get_params(p_details_data)
             if status:
                 break
diff --git a/web/pgadmin/tools/restore/tests/test_create_restore_job.py b/web/pgadmin/tools/restore/tests/test_create_restore_job.py
index 21c485cae..305ebcdd0 100644
--- a/web/pgadmin/tools/restore/tests/test_create_restore_job.py
+++ b/web/pgadmin/tools/restore/tests/test_create_restore_job.py
@@ -115,7 +115,7 @@ class RestoreJobTest(BaseTestGenerator):
 
         cnt = 0
         the_process = None
-        while 1:
+        while True:
             if cnt >= 5:
                 break
             # Check the process list
@@ -165,7 +165,7 @@ class RestoreJobTest(BaseTestGenerator):
 
         # Retrieve the restore job process logs
         cnt = 0
-        while 1:
+        while True:
             out, err, status = RestoreJobTest.get_params(p_details_data)
             if status or cnt >= 5:
                 break
diff --git a/web/pgadmin/tools/schema_diff/directory_compare.py b/web/pgadmin/tools/schema_diff/directory_compare.py
index 59432755b..e082fd92b 100644
--- a/web/pgadmin/tools/schema_diff/directory_compare.py
+++ b/web/pgadmin/tools/schema_diff/directory_compare.py
@@ -396,7 +396,7 @@ def are_lists_identical(source_list, target_list, ignore_whitespaces,
         for index in range(len(source_list)):
             # Check the type of the value if it is an dictionary then
             # call are_dictionaries_identical() function.
-            if type(source_list[index]) is dict:
+            if isinstance(source_list[index], dict):
                 if not are_dictionaries_identical(source_list[index],
                                                   target_list[index],
                                                   ignore_whitespaces,
@@ -444,13 +444,13 @@ def are_dictionaries_identical(source_dict, target_dict, ignore_whitespaces,
         if key in ignore_keys:
             continue
 
-        if type(source_dict[key]) is dict:
+        if isinstance(source_dict[key], dict):
             if not are_dictionaries_identical(source_dict[key],
                                               target_dict[key],
                                               ignore_whitespaces,
                                               ignore_keys):
                 return False
-        elif type(source_dict[key]) is list:
+        elif isinstance(source_dict[key], list):
             # Sort the source and target list on the basis of
             # list key array.
             source_dict[key], target_dict[key] = sort_list(source_dict[key],
@@ -511,18 +511,18 @@ def directory_diff(source_dict, target_dict, ignore_keys=[], difference=None):
         if key in ignore_keys:
             continue
         elif key in tar_only:
-            if type(target_dict[key]) is list:
+            if isinstance(target_dict[key], list):
                 difference[key] = {}
                 difference[key]['deleted'] = target_dict[key]
         elif key in src_only:
             # Source only values in the newly added list
-            if type(source_dict[key]) is list:
+            if isinstance(source_dict[key], list):
                 difference[key] = {}
                 difference[key]['added'] = source_dict[key]
-        elif type(source_dict[key]) is dict:
+        elif isinstance(source_dict[key], dict):
             directory_diff(source_dict[key], target_dict[key],
                            ignore_keys, difference)
-        elif type(source_dict[key]) is list:
+        elif isinstance(source_dict[key], list):
             tmp_target = None
             tmp_list = [x for x in source_dict[key]
                         if isinstance(x, (list, dict))]
@@ -531,10 +531,10 @@ def directory_diff(source_dict, target_dict, ignore_keys=[], difference=None):
                 tmp_target = copy.deepcopy(target_dict[key])
                 for index in range(len(source_dict[key])):
                     source = copy.deepcopy(source_dict[key][index])
-                    if type(source) is list:
+                    if isinstance(source, list):
                         # TODO
                         pass
-                    elif type(source) is dict:
+                    elif isinstance(source, dict):
                         # Check the above keys are exist in the dictionary
                         tmp_key = is_key_exists(list_keys_array, source)
                         if tmp_key is not None:
@@ -549,16 +549,16 @@ def directory_diff(source_dict, target_dict, ignore_keys=[], difference=None):
                         if len(updated) > 0:
                             difference[key]['changed'] = updated
                     elif target_dict[key] is None or \
-                            (type(target_dict[key]) is list and
+                            (isinstance(target_dict[key], list) and
                              len(target_dict[key]) < index and
                              source != target_dict[key][index]):
                         difference[key] = source
-                    elif type(target_dict[key]) is list and\
+                    elif isinstance(target_dict[key], list) and\
                             len(target_dict[key]) > index:
                         difference[key] = source
             elif len(source_dict[key]) > 0:
                 difference[key] = source_dict[key]
-            elif key in target_dict and type(target_dict[key]) is list:
+            elif key in target_dict and isinstance(target_dict[key], list):
                 # If no element in source dict then check for the element
                 # is available in target and the type is of list.
                 # Added such elements as a deleted.
@@ -567,15 +567,15 @@ def directory_diff(source_dict, target_dict, ignore_keys=[], difference=None):
                 if tmp_tar_list:
                     difference[key] = {'deleted': target_dict[key]}
 
-            if type(source) is dict and tmp_target and key in tmp_target and \
+            if isinstance(source, dict) and tmp_target and key in tmp_target and \
                     tmp_target[key] and len(tmp_target[key]) > 0:
-                if type(tmp_target[key]) is list and \
-                        type(tmp_target[key][0]) is dict:
+                if isinstance(tmp_target[key], list) and \
+                        isinstance(tmp_target[key][0], dict):
                     deleted = deleted + tmp_target[key]
                 else:
                     deleted.append({key: tmp_target[key]})
                 difference[key]['deleted'] = deleted
-            elif tmp_target and type(tmp_target) is list:
+            elif tmp_target and isinstance(tmp_target, list):
                 difference[key]['deleted'] = tmp_target
 
             # No point adding empty list into difference.
@@ -620,7 +620,7 @@ def _check_key_in_source_target(key, acl_keys, target, source):
         key = is_key_exists(acl_keys, target)
         if key is None:
             key = 'acl'
-    elif key is not None and type(source[key]) != list:
+    elif key is not None and not isinstance(source[key], list):
         key = 'acl'
 
     return key
@@ -671,13 +671,13 @@ def sort_list(source, target):
     :return:
     """
     # Check the above keys are exist in the dictionary
-    if source is not None and len(source) > 0 and type(source[0]) == dict:
+    if source is not None and source and isinstance(source[0], dict):
         tmp_key = is_key_exists(list_keys_array, source[0])
         if tmp_key is not None:
             source = sorted(source, key=lambda k: k[tmp_key])
 
     # Check the above keys are exist in the dictionary
-    if target is not None and len(target) > 0 and type(target[0]) == dict:
+    if target is not None and target and isinstance(target[0], dict):
         tmp_key = is_key_exists(list_keys_array, target[0])
         if tmp_key is not None:
             target = sorted(target, key=lambda k: k[tmp_key])
@@ -698,7 +698,7 @@ def compare_list_by_ignoring_keys(source_list, target_list, added, updated,
     :param ignore_keys:
     :return:
     """
-    if type(target_list) is list and len(target_list) > 0:
+    if isinstance(target_list, list) and target_list:
         tmp_target = None
         for item in target_list:
             if key in item and item[key] == source_list[key]:
diff --git a/web/pgadmin/tools/sqleditor/__init__.py b/web/pgadmin/tools/sqleditor/__init__.py
index 9f08e472f..b96b98846 100644
--- a/web/pgadmin/tools/sqleditor/__init__.py
+++ b/web/pgadmin/tools/sqleditor/__init__.py
@@ -309,7 +309,7 @@ def extract_sql_from_network_parameters(request_data, request_arguments,
     if request_data:
         sql_parameters = json.loads(request_data, encoding='utf-8')
 
-        if type(sql_parameters) is str:
+        if isinstance(sql_parameters, str):
             return dict(sql=str(sql_parameters), explain_plan=None)
         return sql_parameters
     else:
@@ -616,7 +616,7 @@ def generate_client_primary_key_name(columns_info):
     initial_temp_key_len = len(temp_key)
     duplicate = False
     suffix = 1
-    while 1:
+    while True:
         for col in columns_info:
             if col['name'] == temp_key:
                 duplicate = True
@@ -1414,7 +1414,7 @@ def query_tool_status(trans_id):
     (status, error_msg, conn, trans_obj,
      session_obj) = check_transaction_status(trans_id)
 
-    if not status and error_msg and type(error_msg) == str:
+    if not status and error_msg and isinstance(error_msg, str):
         return internal_server_error(
             errormsg=error_msg
         )
diff --git a/web/pgadmin/tools/sqleditor/command.py b/web/pgadmin/tools/sqleditor/command.py
index 0664be510..cedbe6aa4 100644
--- a/web/pgadmin/tools/sqleditor/command.py
+++ b/web/pgadmin/tools/sqleditor/command.py
@@ -169,7 +169,7 @@ class SQLFilter(object):
         self.did = kwargs['did']
         self.obj_id = kwargs['obj_id']
         sql_filter = kwargs.get('sql_filter', None)
-        self._row_filter = sql_filter if type(sql_filter) is str else None
+        self._row_filter = sql_filter if isinstance(sql_filter, str) else None
         self._data_sorting = kwargs.get('data_sorting', None)
         self._set_sorting_from_filter_dialog = False
 
@@ -212,7 +212,7 @@ class SQLFilter(object):
         Args:
             row_filter: sql query
         """
-        if type(row_filter) is not str:
+        if not isinstance(row_filter, str):
             row_filter = None
 
         status, msg = self.validate_filter(row_filter)
diff --git a/web/pgadmin/tools/sqleditor/utils/start_running_query.py b/web/pgadmin/tools/sqleditor/utils/start_running_query.py
index cddd64ecd..ab845cc51 100644
--- a/web/pgadmin/tools/sqleditor/utils/start_running_query.py
+++ b/web/pgadmin/tools/sqleditor/utils/start_running_query.py
@@ -42,7 +42,7 @@ class StartRunningQuery:
             http_session,
             trans_id
         )
-        if type(session_obj) is Response:
+        if isinstance(session_obj, Response):
             return session_obj
 
         # Remove any existing primary keys or has_oids in session_obj
diff --git a/web/pgadmin/utils/ajax.py b/web/pgadmin/utils/ajax.py
index 7c37d20ed..efebd6257 100644
--- a/web/pgadmin/utils/ajax.py
+++ b/web/pgadmin/utils/ajax.py
@@ -35,7 +35,7 @@ class ColParamsJSONDecoder(json.JSONDecoder):
         retval = obj
         try:
             retval = json.JSONDecoder.decode(self, obj)
-            if type(retval) == str:
+            if isinstance(retval, str):
                 retval = obj
         except (ValueError, TypeError, KeyError):
             retval = obj
diff --git a/web/pgadmin/utils/csv.py b/web/pgadmin/utils/csv.py
index fd67df230..11bb56950 100644
--- a/web/pgadmin/utils/csv.py
+++ b/web/pgadmin/utils/csv.py
@@ -555,7 +555,7 @@ class Dialect(object):
     def validate_text(dialect, attr):
         val = getattr(dialect, attr)
         if not isinstance(val, str):
-            if type(val) == bytes:
+            if isinstance(val, bytes):
                 raise Error('"{0}" must be string, not bytes'.format(attr))
             raise Error('"{0}" must be string, not {1}'.format(
                 attr, type(val).__name__))
diff --git a/web/pgadmin/utils/driver/psycopg2/__init__.py b/web/pgadmin/utils/driver/psycopg2/__init__.py
index 016e585d7..f957c96c8 100644
--- a/web/pgadmin/utils/driver/psycopg2/__init__.py
+++ b/web/pgadmin/utils/driver/psycopg2/__init__.py
@@ -385,7 +385,7 @@ class Driver(BaseDriver):
         value = None
 
         for val in args:
-            if type(val) == list:
+            if isinstance(val, list):
                 return map(lambda w: Driver.qtIdent(conn, w), val)
 
             # DataType doesn't have len function then convert it to string
diff --git a/web/pgadmin/utils/driver/psycopg2/connection.py b/web/pgadmin/utils/driver/psycopg2/connection.py
index 75f46198e..49c87084d 100644
--- a/web/pgadmin/utils/driver/psycopg2/connection.py
+++ b/web/pgadmin/utils/driver/psycopg2/connection.py
@@ -608,7 +608,7 @@ WHERE
         if self.conn and \
             self.conn.encoding in ('SQL_ASCII', 'SQLASCII',
                                    'MULE_INTERNAL', 'MULEINTERNAL')\
-                and params is not None and type(params) == dict:
+                and params is not None and isinstance(params, dict):
             for key, val in params.items():
                 modified_val = val
                 # "unicode_escape" will convert single backslash to double
@@ -1283,7 +1283,7 @@ Failed to reset the connection to the server due to following error:
             conn: connection object
         """
 
-        while 1:
+        while True:
             state = conn.poll()
             if state == psycopg2.extensions.POLL_OK:
                 break
@@ -1309,7 +1309,7 @@ Failed to reset the connection to the server due to following error:
             time: wait time
         """
 
-        while 1:
+        while True:
             state = conn.poll()
 
             if state == psycopg2.extensions.POLL_OK:
diff --git a/web/pgadmin/utils/driver/psycopg2/cursor.py b/web/pgadmin/utils/driver/psycopg2/cursor.py
index e5f663a48..82ec3d592 100644
--- a/web/pgadmin/utils/driver/psycopg2/cursor.py
+++ b/web/pgadmin/utils/driver/psycopg2/cursor.py
@@ -232,7 +232,7 @@ class DictCursor(_cursor):
         it = _cursor.__iter__(self)
         try:
             yield self._dict_tuple(next(it))
-            while 1:
+            while True:
                 yield self._dict_tuple(next(it))
         except StopIteration:
             pass
diff --git a/web/pgadmin/utils/preferences.py b/web/pgadmin/utils/preferences.py
index 8b2ad4c90..5495f019c 100644
--- a/web/pgadmin/utils/preferences.py
+++ b/web/pgadmin/utils/preferences.py
@@ -163,7 +163,7 @@ class _Preference(object):
 
         try:
             if self._type in ('boolean', 'switch', 'node'):
-                assert type(value) == bool
+                assert isinstance(value, bool)
             elif self._type == 'options':
                 has_value = next((True for opt in self.options
                                   if 'value' in opt and opt['value'] == value),
@@ -175,11 +175,11 @@ class _Preference(object):
                 value = parser_map.get(self._type, lambda v: v)(value)
                 if self._type == 'integer':
                     value = self.normalize_range(value)
-                    assert type(value) == int
+                    assert isinstance(value, int)
                 if self._type == 'numeric':
                     value = self.normalize_range(value)
-                    assert (type(value) == int or type(value) == float or
-                            type(value) == decimal.Decimal)
+                    assert (isinstance(value, int) or isinstance(value, float) or
+                            isinstance(value, decimal.Decimal))
         except Exception as e:
             current_app.logger.exception(e)
             return False, gettext(
diff --git a/web/regression/python_test_utils/test_utils.py b/web/regression/python_test_utils/test_utils.py
index 7311f3cdc..6d66af15a 100644
--- a/web/regression/python_test_utils/test_utils.py
+++ b/web/regression/python_test_utils/test_utils.py
@@ -1100,7 +1100,7 @@ def get_server_type(server):
         pg_cursor.execute("SELECT version()")
         version_string = pg_cursor.fetchone()
         connection.close()
-        if type(version_string) == tuple:
+        if isinstance(version_string, tuple):
             version_string = version_string[0]
 
         if "Greenplum Database" in version_string:
diff --git a/web/regression/re_sql/tests/test_resql.py b/web/regression/re_sql/tests/test_resql.py
index 88de458a6..09d4a0801 100644
--- a/web/regression/re_sql/tests/test_resql.py
+++ b/web/regression/re_sql/tests/test_resql.py
@@ -402,7 +402,7 @@ class ReverseEngineeredSQLTestCases(BaseTestGenerator):
             traceback.print_exc()
             return False
         try:
-            if type(response.data) == bytes:
+            if isinstance(response.data, bytes):
                 response_data = response.data.decode('utf8')
                 resp = json.loads(response_data)
             else:
-- 
2.28.0

