Skip to content

Commit 6c6cd78

Browse files
committed
[FIXES] Several fixes related to unicode literals
- Close #1655: fixes the References:: leftover in help() of interfaces - Close #1644: fixes the parameterized paths generated with python 2 - All uses of repr and re-definitions of __repr__ have been revised (again, this is related to #1644, #1621, etc).
1 parent c4c724b commit 6c6cd78

File tree

10 files changed

+43
-54
lines changed

10 files changed

+43
-54
lines changed

nipype/algorithms/modelgen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -547,7 +547,7 @@ def _generate_design(self, infolist=None):
547547
out = np.array([])
548548

549549
if out.size > 0:
550-
iflogger.debug('fname=%s, out=%s, nscans=%s', filename, out, repr(sum(nscans[0:i])))
550+
iflogger.debug('fname=%s, out=%s, nscans=%d', filename, out, sum(nscans[0:i]))
551551
sumscans = out.astype(int) + sum(nscans[0:i])
552552

553553
if out.size == 1:

nipype/caching/memory.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,9 @@ def __call__(self, **kwargs):
9393
return out
9494

9595
def __repr__(self):
96-
return '%s(%s.%s, base_dir=%s)' % (self.__class__.__name__,
97-
self.interface.__module__,
98-
self.interface.__name__,
99-
self.base_dir)
96+
return '{}({}.{}}, base_dir={})'.format(
97+
self.__class__.__name__, self.interface.__module__, self.interface.__name__,
98+
self.base_dir)
10099

101100
################################################################################
102101
# Memory manager: provide some tracking about what is computed when, to
@@ -302,5 +301,4 @@ def _clear_all_but(self, runs, warn=True):
302301
job_names, warn=warn)
303302

304303
def __repr__(self):
305-
return '%s(base_dir=%s)' % (self.__class__.__name__,
306-
self.base_dir)
304+
return '{}(base_dir={})'.format(self.__class__.__name__, self.base_dir)

nipype/external/due.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def nondecorating_decorator(func):
4242
cite = load = add = _donothing
4343

4444
def __repr__(self):
45-
return self.__class__.__name__ + '()'
45+
return '{}()'.format(self.__class__.__name__)
4646

4747

4848
def _donothing_func(*args, **kwargs):

nipype/interfaces/base.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def __init__(self, value):
7272
self.value = value
7373

7474
def __str__(self):
75-
return repr(self.value)
75+
return '{}'.format(self.value)
7676

7777
def _exists_in_path(cmd, environ):
7878
"""
@@ -381,7 +381,7 @@ def __repr__(self):
381381
outstr = []
382382
for name, value in sorted(self.trait_get().items()):
383383
outstr.append('%s = %s' % (name, value))
384-
return '\n' + '\n'.join(outstr) + '\n'
384+
return '\n{}\n'.format('\n'.join(outstr))
385385

386386
def _generate_handlers(self):
387387
"""Find all traits with the 'xor' metadata and attach an event
@@ -808,10 +808,13 @@ def help(cls, returnhelp=False):
808808
def _refs_help(cls):
809809
""" Prints interface references.
810810
"""
811+
if not cls.references_:
812+
return []
813+
811814
helpstr = ['References::']
812815

813816
for r in cls.references_:
814-
helpstr += [repr(r['entry'])]
817+
helpstr += ['{}'.format(r['entry'])]
815818

816819
return helpstr
817820

nipype/interfaces/fsl/dti.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -946,7 +946,7 @@ def _list_outputs(self):
946946
cwd, base_name = os.path.split(name)
947947
outputs['out_files'].append(self._gen_fname(
948948
base_name, cwd=cwd,
949-
suffix='_proj_seg_thr_' + repr(self.inputs.threshold)))
949+
suffix='_proj_seg_thr_{}'.format(self.inputs.threshold)))
950950
return outputs
951951

952952

nipype/pipeline/engine/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def __repr__(self):
105105
if self._hierarchy:
106106
return '.'.join((self._hierarchy, self._id))
107107
else:
108-
return self._id
108+
return '{}'.format(self._id)
109109

110110
def save(self, filename=None):
111111
if filename is None:

nipype/pipeline/engine/nodes.py

Lines changed: 20 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -205,20 +205,16 @@ def output_dir(self):
205205
if self._hierarchy:
206206
outputdir = op.join(outputdir, *self._hierarchy.split('.'))
207207
if self.parameterization:
208+
params_str = ['{}'.format(p) for p in self.parameterization]
208209
if not str2bool(self.config['execution']['parameterize_dirs']):
209-
param_dirs = [self._parameterization_dir(p) for p in
210-
self.parameterization]
211-
outputdir = op.join(outputdir, *param_dirs)
212-
else:
213-
outputdir = op.join(outputdir, *self.parameterization)
210+
params_str = [self._parameterization_dir(p) for p in params_str]
211+
outputdir = op.join(outputdir, *params_str)
214212
return op.abspath(op.join(outputdir,
215213
self.name))
216214

217215
def set_input(self, parameter, val):
218216
""" Set interface input value"""
219-
logger.debug('setting nodelevel(%s) input %s = %s' % (str(self),
220-
parameter,
221-
str(val)))
217+
logger.debug('setting nodelevel(%s) input %s = %s', self.name, parameter, val)
222218
setattr(self.inputs, parameter, deepcopy(val))
223219

224220
def get_output(self, parameter):
@@ -278,7 +274,7 @@ def run(self, updatehash=False):
278274
self._get_inputs()
279275
self._got_inputs = True
280276
outdir = self.output_dir()
281-
logger.info("Executing node %s in dir: %s" % (self._id, outdir))
277+
logger.info("Executing node %s in dir: %s", self._id, outdir)
282278
if op.exists(outdir):
283279
logger.debug(os.listdir(outdir))
284280
hash_info = self.hash_exists(updatehash=updatehash)
@@ -301,25 +297,19 @@ def run(self, updatehash=False):
301297
len(glob(json_unfinished_pat)) == 0)
302298
if need_rerun:
303299
logger.debug("Rerunning node")
304-
logger.debug(("updatehash = %s, "
305-
"self.overwrite = %s, "
306-
"self._interface.always_run = %s, "
307-
"os.path.exists(%s) = %s, "
308-
"hash_method = %s") %
309-
(str(updatehash),
310-
str(self.overwrite),
311-
str(self._interface.always_run),
312-
hashfile,
313-
str(op.exists(hashfile)),
314-
self.config['execution']['hash_method'].lower()))
300+
logger.debug(
301+
"updatehash = %s, self.overwrite = %s, self._interface.always_run = %s, "
302+
"os.path.exists(%s) = %s, hash_method = %s", updatehash, self.overwrite,
303+
self._interface.always_run, hashfile, op.exists(hashfile),
304+
self.config['execution']['hash_method'].lower())
315305
log_debug = config.get('logging', 'workflow_level') == 'DEBUG'
316306
if log_debug and not op.exists(hashfile):
317307
exp_hash_paths = glob(json_pat)
318308
if len(exp_hash_paths) == 1:
319309
split_out = split_filename(exp_hash_paths[0])
320310
exp_hash_file_base = split_out[1]
321311
exp_hash = exp_hash_file_base[len('_0x'):]
322-
logger.debug("Previous node hash = %s" % exp_hash)
312+
logger.debug("Previous node hash = %s", exp_hash)
323313
try:
324314
prev_inputs = load_json(exp_hash_paths[0])
325315
except:
@@ -343,26 +333,26 @@ def run(self, updatehash=False):
343333
self._interface.can_resume) and not
344334
isinstance(self, MapNode))
345335
if rm_outdir:
346-
logger.debug("Removing old %s and its contents" % outdir)
336+
logger.debug("Removing old %s and its contents", outdir)
347337
try:
348338
rmtree(outdir)
349339
except OSError as ex:
350340
outdircont = os.listdir(outdir)
351341
if ((ex.errno == errno.ENOTEMPTY) and (len(outdircont) == 0)):
352-
logger.warn(('An exception was raised trying to remove old %s, '
353-
'but the path seems empty. Is it an NFS mount?. '
354-
'Passing the exception.') % outdir)
342+
logger.warn(
343+
'An exception was raised trying to remove old %s, but the path '
344+
'seems empty. Is it an NFS mount?. Passing the exception.', outdir)
355345
elif ((ex.errno == errno.ENOTEMPTY) and (len(outdircont) != 0)):
356-
logger.debug(('Folder contents (%d items): '
357-
'%s') % (len(outdircont), outdircont))
346+
logger.debug(
347+
'Folder contents (%d items): %s', len(outdircont), outdircont)
358348
raise ex
359349
else:
360350
raise ex
361351

362352
else:
363-
logger.debug(("%s found and can_resume is True or Node is a "
364-
"MapNode - resuming execution") %
365-
hashfile_unfinished)
353+
logger.debug(
354+
"%s found and can_resume is True or Node is a MapNode - resuming execution",
355+
hashfile_unfinished)
366356
if isinstance(self, MapNode):
367357
# remove old json files
368358
for filename in glob(op.join(outdir, '_0x*.json')):

nipype/pipeline/engine/utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,12 +1060,12 @@ def make_output_dir(outdir):
10601060
# this odd approach deals with concurrent directory cureation
10611061
try:
10621062
if not os.path.exists(os.path.abspath(outdir)):
1063-
logger.debug("Creating %s" % outdir)
1063+
logger.debug("Creating %s", outdir)
10641064
os.makedirs(outdir)
10651065
except OSError:
1066-
logger.debug("Problem creating %s" % outdir)
1066+
logger.debug("Problem creating %s", outdir)
10671067
if not os.path.exists(outdir):
1068-
raise OSError('Could not create %s'%outdir)
1068+
raise OSError('Could not create %s', outdir)
10691069
return outdir
10701070

10711071

nipype/pipeline/plugins/sge.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,10 @@ def __init__(self, job_num, job_queue_state, job_time, job_queue_name, job_slots
5151
self._qsub_command_line = qsub_command_line
5252

5353
def __repr__(self):
54-
return str(self._job_num).ljust(8) \
55-
+ str(self._job_queue_state).ljust(12) \
56-
+ str(self._job_slots).ljust(3) \
57-
+ time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(self._job_time)).ljust(20) \
58-
+ str(self._job_queue_name).ljust(8) \
59-
+ str(self._qsub_command_line)
54+
return '{:<8d}{:12}{:<3d}{:20}{:8}{}'.format(
55+
self._job_num, self._queue_state, self._job_slots,
56+
time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(self._job_time)),
57+
self._job_queue_name, self._qsub_command_line)
6058

6159
def is_initializing(self):
6260
return self._job_queue_state == "initializing"

nipype/utils/filemanip.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def encode_dict_py27(value):
111111
nels = len(value)
112112
for i, v in enumerate(value):
113113
venc = encode_dict_py27(v)
114-
if venc.startswith("u'") or venc.startswith('u"'):
114+
if venc.startswith(("u'", 'u"')):
115115
venc = venc[1:]
116116
retval += venc
117117

@@ -124,7 +124,7 @@ def encode_dict_py27(value):
124124
return retval
125125

126126
retval = repr(value).decode()
127-
if retval.startswith("u'") or retval.startswith('u"'):
127+
if retval.startswith(("u'", 'u"')):
128128
retval = retval[1:]
129129
return retval
130130

0 commit comments

Comments
 (0)