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

DM-23178: Update code to use f strings #512

Merged
merged 1 commit into from
Jan 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 5 additions & 7 deletions bin.src/showCamera.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,25 +45,23 @@
#
# Import the obs package and lookup the mapper
#
obsPackageName = "lsst.obs.%s" % args.mapper # guess the package
obsPackageName = f"lsst.obs.{args.mapper}" # guess the package

try:
__import__(obsPackageName)
except Exception:
print("Unable to import %s -- is it setup?" %
(obsPackageName,), file=sys.stderr)
print(f"Unable to import {obsPackageName} -- is it setup?", file=sys.stderr)
sys.exit(1)

# __import__ returns the top-level module, so look ours up
obsPackage = sys.modules[obsPackageName]

mapperName = "%s%sMapper" % (
args.mapper[0].title(), args.mapper[1:]) # guess the name too
# Guess the name too.
mapperName = f"{args.mapper[0].title()}{args.mapper[1:]}Mapper"
try:
mapper = getattr(obsPackage, mapperName)
except AttributeError:
print("Unable to find mapper %s in %s" %
(mapperName, obsPackageName), file=sys.stderr)
print("Unable to find mapper {mapperName} in {obsPackageName}", file=sys.stderr)
sys.exit(1)
#
# Control verbosity from butler
Expand Down
2 changes: 1 addition & 1 deletion examples/catTables.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def concatenate(catalogList):
schema = catalogList[0].schema
for i, c in enumerate(catalogList[1:]):
if c.schema != schema:
raise RuntimeError("Schema for catalog %d not consistent" % (i+1))
raise RuntimeError(f"Schema for catalog {i+1} not consistent")

out = afwTable.BaseCatalog(schema)
num = reduce(lambda n, c: n + len(c), catalogList, 0)
Expand Down
12 changes: 6 additions & 6 deletions python/lsst/afw/cameraGeom/assembleImage.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ def assembleAmplifierImage(destImage, rawImage, amplifier):
if not amplifier.getHasRawInfo():
raise RuntimeError("amplifier must contain raw amplifier info")
if type(destImage.Factory) != type(rawImage.Factory): # noqa: E721
raise RuntimeError("destImage type = %s != %s = rawImage type" %
type(destImage.Factory).__name__, type(rawImage.Factory).__name__)
raise RuntimeError(f"destImage type = {type(destImage.Factory).__name__} != "
f"{type(rawImage.Factory).__name__} = rawImage type")
inView = rawImage.Factory(rawImage, amplifier.getRawDataBBox())
outView = destImage.Factory(destImage, amplifier.getBBox())

Expand Down Expand Up @@ -107,8 +107,8 @@ def assembleAmplifierRawImage(destImage, rawImage, amplifier):
if not amplifier.getHasRawInfo():
raise RuntimeError("amplifier must contain raw amplifier info")
if type(destImage.Factory) != type(rawImage.Factory): # noqa: E721
raise RuntimeError("destImage type = %s != %s = rawImage type" %
type(destImage.Factory).__name__, type(rawImage.Factory).__name__)
raise RuntimeError(f"destImage type = {type(destImage.Factory).__name__} != "
f"{type(rawImage.Factory).__name__} = rawImage type")
inBBox = amplifier.getRawBBox()
inView = rawImage.Factory(rawImage, inBBox)
outBBox = amplifier.getRawBBox()
Expand Down Expand Up @@ -149,14 +149,14 @@ def makeUpdatedDetector(ccd):
"Data",
"VerticalOverscan",
"Prescan"):
bbox = getattr(amp, "getRaw%sBBox" % bboxName)()
bbox = getattr(amp, f"getRaw{bboxName}BBox")()
if amp.getRawFlipX():
bbox.flipLR(awidth)
if amp.getRawFlipY():
bbox.flipTB(aheight)
bbox.shift(amp.getRawXYOffset() + shift)

getattr(amp, "setRaw%sBBox" % bboxName)(bbox)
getattr(amp, f"setRaw{bboxName}BBox")(bbox)
#
# All of these have now been transferred to the per-amp geometry
#
Expand Down
2 changes: 1 addition & 1 deletion python/lsst/afw/cameraGeom/cameraConfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def getCrosstalk(self, numAmps):
try:
return np.array(self.crosstalk, dtype=np.float32).reshape((numAmps, numAmps))
except Exception as e:
raise RuntimeError("Cannot reshape 'crosstalk' coefficients to square matrix: %s" % (e,))
raise RuntimeError(f"Cannot reshape 'crosstalk' coefficients to square matrix: {e}")

@property
def bbox(self):
Expand Down
2 changes: 1 addition & 1 deletion python/lsst/afw/cameraGeom/testUtils.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def __init__(self,
self.ampList = []
for i in range(numAmps):
ampBuilder = Amplifier.Builder()
ampName = "amp %d" % (i + 1,)
ampName = f"amp {i + 1}"
ampBuilder.setName(ampName)
ampBuilder.setBBox(lsst.geom.Box2I(lsst.geom.Point2I(-1, 1), self.ampExtent))
ampBuilder.setGain(1.71234e3)
Expand Down
9 changes: 5 additions & 4 deletions python/lsst/afw/cameraGeom/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,9 +490,10 @@ def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1, asMaskedImag
im = im.getMaskedImage().getImage()
else:
if self.verbose:
print("Reading %s: %s" % (ccd.getId(), err)) # lost by jupyterLab
# Lost by jupyterlab.
print(f"Reading {ccd.getId()}: {err}")

log.warn("Reading %s: %s", ccd.getId(), err)
log.warn(f"Reading {ccd.getId()}: {err}")

if im is None:
return self._prepareImage(ccd, imageFactory(*bbox.getDimensions()), binSize), ccd
Expand All @@ -509,7 +510,7 @@ def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1, asMaskedImag
im = self.callback(im, ccd, imageSource=self)
except Exception as e:
if self.verbose:
log.error("callback failed: %s" % e)
log.error(f"callback failed: {e}")
im = imageFactory(*bbox.getDimensions())
else:
allowRotate = False # the callback was responsible for any rotations
Expand Down Expand Up @@ -926,7 +927,7 @@ def makeImageFromCamera(camera, detectorNameList=None, background=numpy.nan, buf
try:
imView[:] = im
except pexExceptions.LengthError as e:
log.error("Unable to fit image for detector \"%s\" into image of camera: %s" % (det.getName(), e))
log.error(f"Unable to fit image for detector \"{det.getName()}\" into image of camera: {e}")

return camIm

Expand Down
2 changes: 1 addition & 1 deletion python/lsst/afw/display/ds9.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(self, exception):
# don't want to capture in a closure for all time: see DM-9504 for a
# full discussion. We therefore define a new exception of the same
# type, which just encodes the error text.
self.exception = type(exception)("%s (is display_ds9 setup?)" % exception)
self.exception = type(exception)(f"{exception} (is display_ds9 setup?)")

def __call__(self, *args, **kwargs):
raise self.exception
Expand Down
4 changes: 2 additions & 2 deletions python/lsst/afw/display/ds9Regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def dot(symb, c, r, size, ctype=None, fontFamily="helvetica", textAngle=None):
if not fontFamily:
# appears to be needed at least for 7.4b1
fontFamily = ["normal"]
font += " %s" % " ".join(fontFamily)
font += " " + " ".join(fontFamily)
font += '"'
extra = ""
if color or angle or font:
Expand Down Expand Up @@ -134,7 +134,7 @@ def drawLines(points, ctype=None):
if ctype is None: # default
color = ""
else:
color = "# color=%s" % ctype
color = f"# color={ctype}"

regions = []
if len(points) > 0:
Expand Down
24 changes: 12 additions & 12 deletions python/lsst/afw/display/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _makeDisplayImpl(display, backend, *args, **kwargs):
"""
_disp = None
exc = None
for dt in ("lsst.display.%s" % backend, backend, ".%s" % backend, "lsst.afw.display.%s" % backend):
for dt in (f"lsst.display.{backend}", backend, f".{backend}", f"lsst.afw.display.{backend}"):
exc = None
# only specify the root package if we are not doing an absolute import
impargs = {}
Expand Down Expand Up @@ -175,7 +175,7 @@ def __init__(self, frame=None, backend=None, *args, **kwargs):
self._callbacks = {}

for ik in range(ord('a'), ord('z') + 1):
k = "%c" % ik
k = f"{ik:c}"
self.setCallback(k, noRaise=True)
self.setCallback(k.upper(), noRaise=True)

Expand Down Expand Up @@ -233,7 +233,7 @@ def __getattr__(self, name):
return getattr(self._impl, name)
except AttributeError:
raise AttributeError(
"Device %s has no attribute \"%s\"" % (self.name, name))
f"Device {self.name} has no attribute \"{name}\"")

def close(self):
if getattr(self, "_impl", None) is not None:
Expand All @@ -256,7 +256,7 @@ def verbose(self, value):
self._impl.verbose = value

def __str__(self):
return "Display[%s]" % (self.frame)
return f"Display[{self.frame}]"

#
# Handle Displays, including the default one (the frame to use when a user specifies None)
Expand All @@ -267,7 +267,7 @@ def setDefaultBackend(backend):
_makeDisplayImpl(None, backend)
except Exception as e:
raise RuntimeError(
"Unable to set backend to %s: \"%s\"" % (backend, e))
f"Unable to set backend to {backend}: \"{e}\"")

Display._defaultBackend = backend

Expand Down Expand Up @@ -387,7 +387,7 @@ def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kw

if frame not in Display._displays:
if backend == "":
raise RuntimeError("Frame %s does not exist" % frame)
raise RuntimeError(f"Frame {frame} does not exist")

Display._displays[frame] = Display(
frame, backend, verbose=verbose, *args, **kwargs)
Expand Down Expand Up @@ -550,7 +550,7 @@ def mtv(self, data, title="", wcs=None):
elif isinstance(data, afwImage.MaskedImage):
self._impl._mtv(data.getImage(), data.getMask(), wcs, title)
else:
raise RuntimeError("Unsupported type %s" % repr(data))
raise RuntimeError(f"Unsupported type {data!r}")
#
# Graphics commands
#
Expand Down Expand Up @@ -629,7 +629,7 @@ def dot(self, symb, c, r, size=2, ctype=None, origin=afwImage.PARENT, *args, **k
Extra keyword arguments to backend
"""
if isinstance(symb, int):
symb = "%d" % (symb)
symb = f"{symb:d}"

if origin == afwImage.PARENT and self._xy0 is not None:
x0, y0 = self._xy0
Expand Down Expand Up @@ -710,8 +710,8 @@ def scale(self, algorithm, min, max=None, unit=None, *args, **kwargs):
Optional keyword arguments to the backend
"""
if min in ("minmax", "zscale"):
assert max is None, "You may not specify \"%s\" and max" % min
assert unit is None, "You may not specify \"%s\" and unit" % min
assert max is None, f"You may not specify \"{min}\" and max"
assert unit is None, f"You may not specify \"{min}\" and unit"
elif max is None:
raise RuntimeError("Please specify max")

Expand Down Expand Up @@ -802,7 +802,7 @@ def setCallback(self, k, func=None, noRaise=False):
if noRaise:
return
raise RuntimeError(
"Key '%s' is already in use by display, so I can't add a callback for it" % k)
f"Key '{k}' is already in use by display, so I can't add a callback for it")

ofunc = self._callbacks.get(k)
self._callbacks[k] = func if func else noop_callback
Expand Down Expand Up @@ -838,7 +838,7 @@ def __init__(self, k, x=float('nan'), y=float('nan')):
self.y = y

def __str__(self):
return "%s (%.2f, %.2f)" % (self.k, self.x, self.y)
return f"{self.k} ({self.x:.2f}, {self.y:.2f}"
#
# Default fallback function
#
Expand Down
2 changes: 1 addition & 1 deletion python/lsst/afw/display/rgb/rgbContinued.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def makeRgbImage(self, imageR=None, imageG=None, imageB=None,
import scipy.misc
except ImportError as e:
raise RuntimeError(
"Unable to rescale as scipy.misc is unavailable: %s" % e)
f"Unable to rescale as scipy.misc is unavailable: {e}")

for i, im in enumerate(imageRGB):
imageRGB[i] = scipy.misc.imresize(
Expand Down
14 changes: 6 additions & 8 deletions python/lsst/afw/display/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def _getDisplayFromDisplayOrFrame(display, frame=None):
display = None

if display and not hasattr(display, "frame"):
raise RuntimeError("display == %s doesn't support .frame" % display)
raise RuntimeError(f"display == {display} doesn't support .frame")

if frame and display and display.frame != frame:
raise RuntimeError("Please specify display *or* frame")
Expand Down Expand Up @@ -165,7 +165,7 @@ def makeMosaic(self, images=None, display="deferToFrame", mode=None,
if images:
if self.images:
raise RuntimeError(
"You have already appended %d images to this Mosaic" % len(self.images))
f"You have already appended {len(self.images)} images to this Mosaic")

try:
len(images) # check that it quacks like a list
Expand Down Expand Up @@ -217,7 +217,7 @@ def makeMosaic(self, images=None, display="deferToFrame", mode=None,
if nx*ny < self.nImage:
ny += 1
else:
raise RuntimeError("Unknown mosaicing mode: %s" % mode)
raise RuntimeError(f"Unknown mosaicing mode: {mode}")

self.nx, self.ny = nx, ny

Expand All @@ -228,8 +228,7 @@ def makeMosaic(self, images=None, display="deferToFrame", mode=None,
try:
mosaic.set(self.background)
except AttributeError:
raise RuntimeError("Attempt to mosaic images of type %s which don't support set" %
type(mosaic))
raise RuntimeError(f"Attempt to mosaic images of type {type(mosaic)} which don't support set")

for i in range(len(images)):
smosaic = mosaic.Factory(
Expand Down Expand Up @@ -280,7 +279,7 @@ def setMode(self, mode):
"""

if mode not in ("square", "x", "y"):
raise RuntimeError("Unknown mosaicing mode: %s" % mode)
raise RuntimeError(f"Unknown mosaicing mode: {mode}")

self.mode = mode

Expand Down Expand Up @@ -317,8 +316,7 @@ def drawLabels(self, labels=None, display="deferToFrame", frame=None):
return

if len(labels) != self.nImage:
raise RuntimeError("You provided %d labels for %d panels" % (
len(labels), self.nImage))
raise RuntimeError(f"You provided {len(labels)} labels for {self.nImage} panels")

display = _getDisplayFromDisplayOrFrame(display, frame)
if not display:
Expand Down
16 changes: 7 additions & 9 deletions python/lsst/afw/fits/fitsContinued.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,20 @@ def __exit__(self, cls, exc, traceback):
@continueClass # noqa: F811
class ImageWriteOptions:
def __repr__(self):
return "%s(compression=%r, scaling=%r)" % (self.__class__.__name__, self.compression, self.scaling)
return f"{self.__class__.__name__}(compression={self.compression!r}, scaling={self.scaling!r})"


@continueClass # noqa: F811
class ImageCompressionOptions:
def __repr__(self):
return ("%s(algorithm=%r, tiles=%r, quantizeLevel=%f" %
(self.__class__.__name__, compressionAlgorithmToString(self.algorithm),
self.tiles.tolist(), self.quantizeLevel))
return (f"{self.__class__.__name__}(algorithm={compressionAlgorithmToString(self.algorithm)!r}, "
f"tiles={self.tiles.tolist()!r}, quantizeLevel={self.quantizeLevel:f})")


@continueClass # noqa: F811
class ImageScalingOptions:
def __repr__(self):
return ("%s(algorithm=%r, bitpix=%d, maskPlanes=%s, seed=%d, quantizeLevel=%f, quantizePad=%f, "
"fuzz=%s, bscale=%f, bzero=%f" %
(self.__class__.__name__, scalingAlgorithmToString(self.algorithm), self.bitpix,
self.maskPlanes, self.seed, self.quantizeLevel, self.quantizePad, self.fuzz,
self.bscale, self.bzero))
return (f"{self.__class__.__name__}(algorithm={scalingAlgorithmToString(self.algorithm)!r}, "
f"bitpix={self.bitpix}, maskPlanes={self.maskPlanes}, seed={self.seed} "
f"quantizeLevel={self.quantizeLevel}, quantizePad={self.quantizePad}, "
f"fuzz={self.fuzz}, bscale={self.bscale}, bzero={self.bzero})")
4 changes: 2 additions & 2 deletions python/lsst/afw/geom/ellipses/axes/axesContinued.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
@continueClass # noqa: F811
class Axes:
def __repr__(self):
return "Axes(a=%r, b=%r, theta=%r)" % (self.getA(), self.getB(), self.getTheta())
return f"Axes(a={self.getA()!r}, b={self.getB()!r}, theta={self.getTheta!r})"

def __str__(self):
return "(a=%s, b=%s, theta=%s)" % (self.getA(), self.getB(), self.getTheta())
return f"(a={self.getA()}, b={self.getB()}, theta={self.getTheta})"

def __reduce__(self):
return (Axes, (self.getA(), self.getB(), self.getTheta()))
4 changes: 2 additions & 2 deletions python/lsst/afw/geom/ellipses/ellipse/ellipseContinued.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
@continueClass # noqa: F811
class Ellipse:
def __repr__(self):
return "Ellipse(%r, %r)" % (self.getCore(), self.getCenter())
return f"Ellipse({self.getCore()!r}, {self.getCenter()!r})"

def __reduce__(self):
return (Ellipse, (self.getCore(), self.getCenter()))

def __str__(self):
return "(%s, %s)" % (self.getCore(), self.getCenter())
return f"({self.getCore()}, {self.getCenter()})"
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
@continueClass # noqa: F811
class Quadrupole:
def __repr__(self):
return "Quadrupole(ixx=%r, iyy=%r, ixy=%r)" % (self.getIxx(), self.getIyy(), self.getIxy())
return f"Quadrupole(ixx={self.getIxx()!r}, iyy={self.getIyy()!r}, ixy={self.getIxy()!r})"

def __reduce__(self):
return (Quadrupole, (self.getIxx(), self.getIyy(), self.getIxy()))

def __str__(self):
return "(ixx=%s, iyy=%s, ixy=%s)" % (self.getIxx(), self.getIyy(), self.getIxy())
return f"(ixx={self.getIxx()}, iyy={self.getIyy()}, ixy={self.getIxy()})"
2 changes: 1 addition & 1 deletion python/lsst/afw/geom/polygon/polygonContinued.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
@continueClass # noqa: F811
class Polygon:
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, [p for p in self.getVertices()])
return f"{self.__class__.__name__}({[p for p in self.getVertices()]})"

def __reduce__(self):
return self.__class__, (self.getVertices(),)
Expand Down