Skip to content

Commit

Permalink
Merge pull request easybuilders#4412 from Flamefire/cleanup-attr
Browse files Browse the repository at this point in the history
clean up uses of `getattr` and `hasattr`
  • Loading branch information
boegel authored Jan 3, 2024
2 parents faf8086 + 3830181 commit 00a3f52
Show file tree
Hide file tree
Showing 12 changed files with 53 additions and 52 deletions.
2 changes: 1 addition & 1 deletion easybuild/base/fancylogger.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def makeRecord(self, name, level, pathname, lineno, msg, args, excinfo, func=Non
overwrite make record to use a fancy record (with more options)
"""
logrecordcls = logging.LogRecord
if hasattr(self, 'fancyrecord') and self.fancyrecord:
if getattr(self, 'fancyrecord', None):
logrecordcls = FancyLogRecord
try:
new_msg = str(msg)
Expand Down
2 changes: 1 addition & 1 deletion easybuild/base/generaloption.py
Original file line number Diff line number Diff line change
Expand Up @@ -1031,7 +1031,7 @@ def main_options(self):
# make_init is deprecated
if hasattr(self, 'make_init'):
self.log.debug('main_options: make_init is deprecated. Rename function to main_options.')
getattr(self, 'make_init')()
self.make_init()
else:
# function names which end with _options and do not start with main or _
reg_main_options = re.compile("^(?!_|main).*_options$")
Expand Down
21 changes: 10 additions & 11 deletions easybuild/base/optcomplete.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,14 +513,15 @@ def autocomplete(parser, arg_completer=None, opt_completer=None, subcmd_complete
if option:
if option.nargs > 0:
optarg = True
if hasattr(option, 'completer'):
try:
completer = option.completer
elif option.choices:
completer = ListCompleter(option.choices)
elif option.type in ('string',):
completer = opt_completer
else:
completer = NoneCompleter()
except AttributeError:
if option.choices:
completer = ListCompleter(option.choices)
elif option.type in ('string',):
completer = opt_completer
else:
completer = NoneCompleter()
# Warn user at least, it could help him figure out the problem.
elif hasattr(option, 'completer'):
msg = "Error: optparse option with a completer does not take arguments: %s" % (option)
Expand Down Expand Up @@ -616,11 +617,9 @@ class CmdComplete(object):
def autocomplete(self, completer=None):
parser = OPTIONPARSER_CLASS(self.__doc__.strip())
if hasattr(self, 'addopts'):
fnc = getattr(self, 'addopts')
fnc(parser)
self.addopts(parser)

if hasattr(self, 'completer'):
completer = getattr(self, 'completer')
completer = getattr(self, 'completer', completer)

return autocomplete(parser, completer)

Expand Down
11 changes: 6 additions & 5 deletions easybuild/framework/easyconfig/format/pyheaderconfigobj.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,12 +233,13 @@ def pyheader_env(self):
current_builtins = globals()['__builtins__']
builtins = {}
for name in self.PYHEADER_ALLOWED_BUILTINS:
if hasattr(current_builtins, name):
try:
builtins[name] = getattr(current_builtins, name)
elif isinstance(current_builtins, dict) and name in current_builtins:
builtins[name] = current_builtins[name]
else:
self.log.warning('No builtin %s found.' % name)
except AttributeError:
if isinstance(current_builtins, dict) and name in current_builtins:
builtins[name] = current_builtins[name]
else:
self.log.warning('No builtin %s found.' % name)
global_vars['__builtins__'] = builtins
self.log.debug("Available builtins: %s" % global_vars['__builtins__'])

Expand Down
2 changes: 1 addition & 1 deletion easybuild/tools/configobj.py
Original file line number Diff line number Diff line change
Expand Up @@ -1254,7 +1254,7 @@ def set_section(in_section, this_section):
self.configspec = None
return

elif getattr(infile, 'read', MISSING) is not MISSING:
elif hasattr(infile, 'read'):
# This supports file like objects
infile = infile.read() or []
# needs splitting into lines - but needs doing *after* decoding
Expand Down
7 changes: 3 additions & 4 deletions easybuild/tools/docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1250,10 +1250,9 @@ def avail_toolchain_opts(name, output_format=FORMAT_TXT):

tc_dict = {}
for cst in ['COMPILER_SHARED_OPTS', 'COMPILER_UNIQUE_OPTS', 'MPI_SHARED_OPTS', 'MPI_UNIQUE_OPTS']:
if hasattr(tc, cst):
opts = getattr(tc, cst)
if opts is not None:
tc_dict.update(opts)
opts = getattr(tc, cst, None)
if opts is not None:
tc_dict.update(opts)

return generate_doc('avail_toolchain_opts_%s' % output_format, [name, tc_dict])

Expand Down
4 changes: 2 additions & 2 deletions easybuild/tools/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -719,9 +719,9 @@ def setup_repo_from(git_repo, github_url, target_account, branch_name, silent=Fa
raise EasyBuildError("Fetching branch '%s' from remote %s failed: empty result", branch_name, origin)

# git checkout -b <branch>; git pull
if hasattr(origin.refs, branch_name):
try:
origin_branch = getattr(origin.refs, branch_name)
else:
except AttributeError:
raise EasyBuildError("Branch '%s' not found at %s", branch_name, github_url)

_log.debug("Checking out branch '%s' from remote %s", branch_name, github_url)
Expand Down
4 changes: 2 additions & 2 deletions easybuild/tools/systemtools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1340,8 +1340,8 @@ def det_pypkg_version(pkg_name, imported_pkg, import_name=None):
except pkg_resources.DistributionNotFound as err:
_log.debug("%s Python package not found: %s", pkg_name, err)

if version is None and hasattr(imported_pkg, '__version__'):
version = imported_pkg.__version__
if version is None:
version = getattr(imported_pkg, '__version__', None)

return version

Expand Down
10 changes: 5 additions & 5 deletions easybuild/tools/toolchain/linalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,9 @@ def _set_blacs_variables(self):
"""Set BLACS related variables"""

lib_map = {}
if hasattr(self, 'BLAS_LIB_MAP') and self.BLAS_LIB_MAP is not None:
if getattr(self, 'BLAS_LIB_MAP', None) is not None:
lib_map.update(self.BLAS_LIB_MAP)
if hasattr(self, 'BLACS_LIB_MAP') and self.BLACS_LIB_MAP is not None:
if getattr(self, 'BLACS_LIB_MAP', None) is not None:
lib_map.update(self.BLACS_LIB_MAP)

# BLACS
Expand Down Expand Up @@ -254,11 +254,11 @@ def _set_scalapack_variables(self):
raise EasyBuildError("_set_blas_variables: SCALAPACK_LIB not set")

lib_map = {}
if hasattr(self, 'BLAS_LIB_MAP') and self.BLAS_LIB_MAP is not None:
if getattr(self, 'BLAS_LIB_MAP', None) is not None:
lib_map.update(self.BLAS_LIB_MAP)
if hasattr(self, 'BLACS_LIB_MAP') and self.BLACS_LIB_MAP is not None:
if getattr(self, 'BLACS_LIB_MAP', None) is not None:
lib_map.update(self.BLACS_LIB_MAP)
if hasattr(self, 'SCALAPACK_LIB_MAP') and self.SCALAPACK_LIB_MAP is not None:
if getattr(self, 'SCALAPACK_LIB_MAP', None) is not None:
lib_map.update(self.SCALAPACK_LIB_MAP)

self.SCALAPACK_LIB = self.variables.nappend('LIBSCALAPACK_ONLY', [x % lib_map for x in self.SCALAPACK_LIB])
Expand Down
24 changes: 14 additions & 10 deletions easybuild/tools/toolchain/toolchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,13 +163,13 @@ def _is_toolchain_for(cls, name):
"""see if this class can provide support for toolchain named name"""
# TODO report later in the initialization the found version
if name:
if hasattr(cls, 'NAME') and name == cls.NAME:
return True
else:
try:
return name == cls.NAME
except AttributeError:
return False
else:
# is no name is supplied, check whether class can be used as a toolchain
return hasattr(cls, 'NAME') and cls.NAME
return bool(getattr(cls, 'NAME', None))

_is_toolchain_for = classmethod(_is_toolchain_for)

Expand Down Expand Up @@ -330,10 +330,12 @@ def _copy_class_constants(self):
if key not in self.CLASS_CONSTANT_COPIES:
self.CLASS_CONSTANT_COPIES[key] = {}
for cst in self.CLASS_CONSTANTS_TO_RESTORE:
if hasattr(self, cst):
self.CLASS_CONSTANT_COPIES[key][cst] = copy.deepcopy(getattr(self, cst))
else:
try:
value = getattr(self, cst)
except AttributeError:
raise EasyBuildError("Class constant '%s' to be restored does not exist in %s", cst, self)
else:
self.CLASS_CONSTANT_COPIES[key][cst] = copy.deepcopy(value)

self.log.devel("Copied class constants: %s", self.CLASS_CONSTANT_COPIES[key])

Expand All @@ -342,10 +344,12 @@ def _restore_class_constants(self):
key = self.__class__
for cst in self.CLASS_CONSTANT_COPIES[key]:
newval = copy.deepcopy(self.CLASS_CONSTANT_COPIES[key][cst])
if hasattr(self, cst):
self.log.devel("Restoring class constant '%s' to %s (was: %s)", cst, newval, getattr(self, cst))
else:
try:
oldval = getattr(self, cst)
except AttributeError:
self.log.devel("Restoring (currently undefined) class constant '%s' to %s", cst, newval)
else:
self.log.devel("Restoring class constant '%s' to %s (was: %s)", cst, newval, oldval)

setattr(self, cst, newval)

Expand Down
11 changes: 6 additions & 5 deletions easybuild/tools/toolchain/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def search_toolchain(name):
package = easybuild.tools.toolchain
check_attr_name = '%s_PROCESSED' % TC_CONST_PREFIX

if not hasattr(package, check_attr_name) or not getattr(package, check_attr_name):
if not getattr(package, check_attr_name, None):
# import all available toolchains, so we know about them
tc_modules = import_available_modules('easybuild.toolchains')

Expand All @@ -76,7 +76,7 @@ def search_toolchain(name):
if hasattr(elem, '__module__'):
# exclude the toolchain class defined in that module
if not tc_mod.__file__ == sys.modules[elem.__module__].__file__:
elem_name = elem.__name__ if hasattr(elem, '__name__') else elem
elem_name = getattr(elem, '__name__', elem)
_log.debug("Adding %s to list of imported classes used for looking for constants", elem_name)
mod_classes.append(elem)

Expand All @@ -89,13 +89,14 @@ def search_toolchain(name):
tc_const_value = getattr(mod_class_mod, elem)
_log.debug("Found constant %s ('%s') in module %s, adding it to %s",
tc_const_name, tc_const_value, mod_class_mod.__name__, package.__name__)
if hasattr(package, tc_const_name):
try:
cur_value = getattr(package, tc_const_name)
except AttributeError:
setattr(package, tc_const_name, tc_const_value)
else:
if not tc_const_value == cur_value:
raise EasyBuildError("Constant %s.%s defined as '%s', can't set it to '%s'.",
package.__name__, tc_const_name, cur_value, tc_const_value)
else:
setattr(package, tc_const_name, tc_const_value)

# indicate that processing of toolchain constants is done, so it's not done again
setattr(package, check_attr_name, True)
Expand Down
7 changes: 2 additions & 5 deletions test/framework/systemtools.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,17 +366,14 @@ def setUp(self):
self.orig_is_readable = st.is_readable
self.orig_read_file = st.read_file
self.orig_run_cmd = st.run_cmd
self.orig_platform_dist = st.platform.dist if hasattr(st.platform, 'dist') else None
self.orig_platform_dist = getattr(st.platform, 'dist', None)
self.orig_platform_uname = st.platform.uname
self.orig_get_tool_version = st.get_tool_version
self.orig_sys_version_info = st.sys.version_info
self.orig_HAVE_ARCHSPEC = st.HAVE_ARCHSPEC
self.orig_HAVE_DISTRO = st.HAVE_DISTRO
self.orig_ETC_OS_RELEASE = st.ETC_OS_RELEASE
if hasattr(st, 'archspec_cpu_host'):
self.orig_archspec_cpu_host = st.archspec_cpu_host
else:
self.orig_archspec_cpu_host = None
self.orig_archspec_cpu_host = getattr(st, 'archspec_cpu_host', None)

def tearDown(self):
"""Cleanup after systemtools test."""
Expand Down

0 comments on commit 00a3f52

Please sign in to comment.