Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RF/MNT: Remove some rust #915

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/nib-nifti-dx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
''' Print nifti diagnostics for header files '''
""" Print nifti diagnostics for header files """

from nibabel.cmdline.nifti_dx import main

Expand Down
2 changes: 1 addition & 1 deletion doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@

# General information about the project.
project = u'NiBabel'
copyright = u'2006-2020, %(maintainer)s <%(author_email)s>' % metadata
copyright = f"2006-2020, {metadata['maintainer']} <{metadata['author_email']}>"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down
12 changes: 5 additions & 7 deletions doc/source/devel/register_me.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
from os.path import join as pjoin, expanduser, abspath, dirname
import sys
# Python 3 compatibility
try:
import configparser as cfp
except ImportError:
import ConfigParser as cfp
import configparser as cfp


if sys.platform == 'win32':
HOME_INI = pjoin(expanduser('~'), '_dpkg', 'local.dsource')
Expand All @@ -15,6 +12,7 @@
OUR_META = pjoin(OUR_PATH, 'meta.ini')
DISCOVER_INIS = {'user': HOME_INI, 'system': SYS_INI}


def main():
# Get ini file to which to write
try:
Expand All @@ -23,7 +21,7 @@ def main():
reg_to = 'user'
if reg_to in ('user', 'system'):
ini_fname = DISCOVER_INIS[reg_to]
else: # it is an ini file name
else: # it is an ini file name
ini_fname = reg_to

# Read parameters for our distribution
Expand All @@ -42,7 +40,7 @@ def main():
dsource.set(name, version, OUR_PATH)
dsource.write(file(ini_fname, 'wt'))

print 'Registered package %s, %s to %s' % (name, version, ini_fname)
print(f'Registered package {name}, {version} to {ini_fname}')


if __name__ == '__main__':
Expand Down
2 changes: 1 addition & 1 deletion doc/source/dicom/derivations/dicom_mosaic.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
''' Just showing the mosaic simplification '''
""" Just showing the mosaic simplification """
import sympy
from sympy import Matrix, Symbol, symbols, zeros, ones, eye

Expand Down
4 changes: 2 additions & 2 deletions doc/source/dicom/derivations/spm_dicom_orient.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
''' Symbolic versions of the DICOM orientation mathemeatics.
""" Symbolic versions of the DICOM orientation mathemeatics.

Notes on the SPM orientation machinery.

There are symbolic versions of the code in ``spm_dicom_convert``,
``write_volume`` subfunction, around line 509 in the version I have
(SPM8, late 2009 vintage).
'''
"""

import numpy as np

Expand Down
47 changes: 23 additions & 24 deletions doc/tools/apigen.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@


class ApiDocWriter(object):
''' Class for automatic detection and parsing of API docs
to Sphinx-parsable reST format'''
""" Class for automatic detection and parsing of API docs
to Sphinx-parsable reST format"""

# only separating first two levels
rst_section_levels = ['*', '=', '-', '~', '^']
Expand All @@ -42,7 +42,7 @@ def __init__(self,
module_skip_patterns=None,
other_defines=True
):
''' Initialize package for parsing
""" Initialize package for parsing

Parameters
----------
Expand Down Expand Up @@ -70,7 +70,7 @@ def __init__(self,
other_defines : {True, False}, optional
Whether to include classes and functions that are imported in a
particular module but not defined there.
'''
"""
if package_skip_patterns is None:
package_skip_patterns = ['\\.tests$']
if module_skip_patterns is None:
Expand All @@ -85,7 +85,7 @@ def get_package_name(self):
return self._package_name

def set_package_name(self, package_name):
''' Set package_name
""" Set package_name

>>> docwriter = ApiDocWriter('sphinx')
>>> import sphinx
Expand All @@ -95,7 +95,7 @@ def set_package_name(self, package_name):
>>> import docutils
>>> docwriter.root_path == docutils.__path__[0]
True
'''
"""
# It's also possible to imagine caching the module parsing here
self._package_name = package_name
root_module = self._import(package_name)
Expand All @@ -106,30 +106,30 @@ def set_package_name(self, package_name):
'get/set package_name')

def _import(self, name):
''' Import namespace package '''
""" Import namespace package """
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod

def _get_object_name(self, line):
''' Get second token in line
""" Get second token in line
>>> docwriter = ApiDocWriter('sphinx')
>>> docwriter._get_object_name(" def func(): ")
'func'
>>> docwriter._get_object_name(" class Klass(object): ")
'Klass'
>>> docwriter._get_object_name(" class Klass: ")
'Klass'
'''
"""
name = line.split()[1].split('(')[0].strip()
# in case we have classes which are not derived from object
# ie. old style classes
return name.rstrip(':')

def _uri2path(self, uri):
''' Convert uri to absolute filepath
""" Convert uri to absolute filepath

Parameters
----------
Expand All @@ -155,7 +155,7 @@ def _uri2path(self, uri):
True
>>> docwriter._uri2path('sphinx.does_not_exist')

'''
"""
if uri == self.package_name:
return os.path.join(self.root_path, '__init__.py')
path = uri.replace(self.package_name + '.', '')
Expand All @@ -171,15 +171,15 @@ def _uri2path(self, uri):
return path

def _path2uri(self, dirpath):
''' Convert directory path to uri '''
""" Convert directory path to uri """
package_dir = self.package_name.replace('.', os.path.sep)
relpath = dirpath.replace(self.root_path, package_dir)
if relpath.startswith(os.path.sep):
relpath = relpath[1:]
return relpath.replace(os.path.sep, '.')

def _parse_module(self, uri):
''' Parse module defined in *uri* '''
""" Parse module defined in *uri* """
filename = self._uri2path(uri)
if filename is None:
print(filename, 'erk')
Expand Down Expand Up @@ -233,7 +233,7 @@ def _parse_module_with_import(self, uri):
return functions, classes

def _parse_lines(self, linesource):
''' Parse lines of text for functions and classes '''
""" Parse lines of text for functions and classes """
functions = []
classes = []
for line in linesource:
Expand All @@ -254,7 +254,7 @@ def _parse_lines(self, linesource):
return functions, classes

def generate_api_doc(self, uri):
'''Make autodoc documentation template string for a module
"""Make autodoc documentation template string for a module

Parameters
----------
Expand All @@ -267,7 +267,7 @@ def generate_api_doc(self, uri):
Module name, table of contents.
body : string
Function and class docstrings.
'''
"""
# get the names of all classes and functions
functions, classes = self._parse_module_with_import(uri)
if not len(functions) and not len(classes) and DEBUG:
Expand Down Expand Up @@ -317,7 +317,7 @@ def generate_api_doc(self, uri):
return head, body

def _survives_exclude(self, matchstr, match_type):
''' Returns True if *matchstr* does not match patterns
""" Returns True if *matchstr* does not match patterns

``self.package_name`` removed from front of string if present

Expand All @@ -336,14 +336,13 @@ def _survives_exclude(self, matchstr, match_type):
>>> dw.module_skip_patterns.append('^\\.badmod$')
>>> dw._survives_exclude('sphinx.badmod', 'module')
False
'''
"""
if match_type == 'module':
patterns = self.module_skip_patterns
elif match_type == 'package':
patterns = self.package_skip_patterns
else:
raise ValueError('Cannot interpret match type "%s"'
% match_type)
raise ValueError(f'Cannot interpret match type "{match_type}"')
# Match to URI without package name
L = len(self.package_name)
if matchstr[:L] == self.package_name:
Expand All @@ -359,7 +358,7 @@ def _survives_exclude(self, matchstr, match_type):
return True

def discover_modules(self):
''' Return module sequence discovered from ``self.package_name``
""" Return module sequence discovered from ``self.package_name``


Parameters
Expand All @@ -381,7 +380,7 @@ def discover_modules(self):
>>> 'sphinx.util' in dw.discover_modules()
False
>>>
'''
"""
modules = [self.package_name]
# raw directory parsing
for dirpath, dirnames, filenames in os.walk(self.root_path):
Expand Down Expand Up @@ -424,7 +423,7 @@ def write_modules_api(self, modules, outdir):
written_modules = []

for ulm, mods in module_by_ulm.items():
print("Generating docs for %s:" % ulm)
print(f"Generating docs for {ulm}:")
document_head = []
document_body = []

Expand Down Expand Up @@ -505,5 +504,5 @@ def write_index(self, outdir, froot='gen', relative_to=None):
w("=" * len(title) + "\n\n")
w('.. toctree::\n\n')
for f in self.written_modules:
w(' %s\n' % os.path.join(relpath, f))
w(f' {os.path.join(relpath, f)}\n')
idx.close()
2 changes: 1 addition & 1 deletion doc/tools/build_modref_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@


def abort(error):
print('*WARNING* API documentation not generated: %s' % error)
print(f'*WARNING* API documentation not generated: {error}')
exit(1)


Expand Down
7 changes: 3 additions & 4 deletions nibabel/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,12 @@
from .minc2 import Minc2Image
from .cifti2 import Cifti2Header, Cifti2Image
from .gifti import GiftiImage
from .minc1 import MincImage
from .freesurfer import MGHImage
from .funcs import (squeeze_image, concat_images, four_to_three,
as_closest_canonical)
from .orientations import (io_orientation, orientation_affine,
flip_axis, OrientationError,
apply_orientation, aff2axcodes)
from .orientations import (io_orientation, flip_axis,
OrientationError, apply_orientation,
aff2axcodes)
from .imageclasses import class_map, ext_map, all_image_classes
from .deprecated import ModuleProxy as _ModuleProxy
trackvis = _ModuleProxy('nibabel.trackvis')
Expand Down
27 changes: 13 additions & 14 deletions nibabel/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,20 +87,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % dispcmd)
print(f"unable to run {dispcmd}")
print(e)
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
print(f"unable to find command, tried {commands}")
return None, None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
print("stdout was %s" % stdout)
print(f"unable to run {dispcmd} (error)")
print(f"stdout was {stdout}")
return None, p.returncode
return stdout, p.returncode

Expand Down Expand Up @@ -201,9 +201,9 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r'\d', r)])
if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags))
print(f"discarding '{','.join(refs - tags)}', no digits")
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
print(f"likely tags: {','.join(sorted(tags))}")
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
Expand All @@ -214,7 +214,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not re.match(r'\d', r):
continue
if verbose:
print("picking %s" % r)
print(f"picking {r}")
return {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None,
Expand Down Expand Up @@ -243,14 +243,14 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
hide_stderr=True)
if rc != 0:
if verbose:
print("Directory %s not under git control" % root)
print(f"Directory {root} not under git control")
raise NotThisMethod("'git rev-parse --git-dir' returned error")

# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
"--match", f"{tag_prefix}*"],
cwd=root)
# --long was added in git-1.5.5
if describe_out is None:
Expand Down Expand Up @@ -283,8 +283,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
pieces["error"] = (f"unable to parse git-describe output: '{describe_out}'")
return pieces

# tag
Expand Down Expand Up @@ -384,13 +383,13 @@ def render_pep440_post(pieces):
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
rendered += f"g{pieces['short']}"
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
rendered += f"+g{pieces['short']}"
return rendered


Expand Down Expand Up @@ -481,7 +480,7 @@ def render(pieces, style):
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%s'" % style)
raise ValueError(f"unknown style '{style}'")

return {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None,
Expand Down
Loading