Skip to content

Commit

Permalink
Remove some outdated syntax constructs
Browse files Browse the repository at this point in the history
  • Loading branch information
gb119 committed Jan 1, 2024
1 parent bb7d58d commit ee19dbb
Show file tree
Hide file tree
Showing 24 changed files with 1,218 additions and 1,222 deletions.
2 changes: 1 addition & 1 deletion Stoner/Analysis.py
Expand Up @@ -66,7 +66,7 @@ def func(row,**kargs):
if col is None:
col = self.setas.get("y", [0])[0]
col = self.find_col(col)
kargs.update(kargs.pop("_extra", dict()))
kargs.update(kargs.pop("_extra", {}))
# Check the dimension of the output
ret = func(next(self.rows()), **kargs)
try:
Expand Down
4 changes: 2 additions & 2 deletions Stoner/HDF5.py
Expand Up @@ -132,7 +132,7 @@ def load_hdf(new_data, filename, *args, **kargs): # pylint: disable=unused-argu
metadata = f.require_group("metadata")
typehints = f.get("typehints", None)
if not isinstance(typehints, h5py.Group):
typehints = dict()
typehints = {}
else:
typehints = typehints.attrs
if "column_headers" in f.attrs:
Expand Down Expand Up @@ -486,7 +486,7 @@ def read_hdf(cls, filename, *args, **kargs): # pylint: disable=unused-argument
metadata = f.require_group("metadata")
typehints = f.get("typehints", None)
if not isinstance(typehints, h5py.Group):
typehints = dict()
typehints = {}
else:
typehints = typehints.attrs
if "column_headers" in f.attrs:
Expand Down
18 changes: 7 additions & 11 deletions Stoner/Image/util.py
Expand Up @@ -52,14 +52,14 @@ def sign_loss(dtypeobj_in, dtypeobj):
if Options().warnings:
warn(
"Possible sign loss when converting negative image of type "
"%s to positive image of type %s." % (dtypeobj_in, dtypeobj)
f"{dtypeobj_in} to positive image of type {dtypeobj}."
)


def prec_loss(dtypeobj_in, dtypeobj):
"""Warn over precision loss when converting image."""
if Options().warnings:
warn("Possible precision loss when converting from " "%s to %s" % (dtypeobj_in, dtypeobj))
warn(f"Possible precision loss when converting from {dtypeobj_in} to {dtypeobj}")


def _dtype(itemsize, *dtypes):
Expand All @@ -82,21 +82,17 @@ def _scale(a, n, m, dtypeobj_in, dtypeobj, copy=True):
"""Scaleunsigned/positive integers from n to m bits.
Numbers can be represented exactly only if m is a multiple of n
Output array is of same kind as input."""
Output array is of same kind as input.
"""
kind = a.dtype.kind
if n > m and a.max() <= 2**m:
mnew = int(np.ceil(m / 2) * 2)
if mnew > m:
dtype = "int%s" % mnew
dtype = f"int{mnew}"
else:
dtype = "uint%s" % mnew
dtype = f"uint{mnew}"
n = int(np.ceil(n / 2) * 2)
msg = "Downcasting %s to %s without scaling because max " "value %s fits in %s" % (
a.dtype,
dtype,
a.max(),
dtype,
)
msg = f"Downcasting {a.dtype} to {dtype} without scaling because max value {a.max()} fits in{dtype}"
if Options().warnings:
warn(msg)
return a.astype(_dtype2(kind, m))
Expand Down
6 changes: 3 additions & 3 deletions Stoner/analysis/fitting/mixins.py
Expand Up @@ -29,7 +29,7 @@ class odr_Model(odrModel):

def __init__(self, *args, **kargs):
"""Initialise with lmfit.models.Model or callable."""
meta = kargs.pop("meta", dict())
meta = kargs.pop("meta", {})
kargs = copy(kargs)
for n in list(kargs.keys()):
if n in ["replace", "header", "result", "output", "residuals", "prefix"]:
Expand Down Expand Up @@ -359,7 +359,7 @@ def _curve_fit_p0_list(p0, model):
return p0

if isinstance(p0, Mapping):
p_new = dict()
p_new = {}
for x, v in p0.items():
p_new[x] = getattr(v, "value", float(v))
ret = []
Expand Down Expand Up @@ -957,7 +957,7 @@ def _odr_one(self, data, model, prefix, _, **kargs):
Reason(s) for Halting:
"""
for r in fit_result.stopreason:
tmp += " %s\n" % r
tmp += f" {r}\n"
tmp += f""""Sum of orthogonal distance (~chi^2):{fit_result.chisqr}
Reduced Sum of Orthogonal distances (~reduced chi^2): {fit_result.redchi}"""

Expand Down
2 changes: 1 addition & 1 deletion Stoner/analysis/fitting/models/__init__.py
Expand Up @@ -303,7 +303,7 @@ def cfg_model_from_ini(inifile, model=None, data=None):
"label": str,
"units": str,
}
kargs = dict()
kargs = {}
for k in keys:
if config.has_option(p, k):
if keys[k] == bool:
Expand Down
8 changes: 4 additions & 4 deletions Stoner/core/base.py
Expand Up @@ -340,10 +340,10 @@ def __init__(self, *args: Any, **kargs: Any) -> None:
Args:
*args, **kargs:
Pass any parameters through to the dict() constructor.
Pass any parameters through to the {} constructor.
Calls the dict() constructor, then runs through the keys of the
Calls the {} constructor, then runs through the keys of the
created dictionary and either uses the string type embedded in
the keyname to generate the type hint (and remove the
embedded string type from the keyname) or determines the likely
Expand Down Expand Up @@ -675,7 +675,7 @@ class metadataObject(MutableMapping):
def __new__(cls, *args):
"""Pre initialisation routines."""
self = super().__new__(cls)
self._public_attrs_real = dict()
self._public_attrs_real = {}
self._metadata = typeHintedDict()
return self

Expand All @@ -692,7 +692,7 @@ def _public_attrs(self):
try:
return self._public_attrs_real # pylint: disable=no-member
except AttributeError:
self._public_attrs_real = dict() # pylint: disable=attribute-defined-outside-init
self._public_attrs_real = {} # pylint: disable=attribute-defined-outside-init
return self._public_attrs_real

@_public_attrs.setter
Expand Down
4 changes: 2 additions & 2 deletions Stoner/core/methods.py
Expand Up @@ -151,7 +151,7 @@ def find_duplicates(self, xcol=None, delta=1e-8):
delta = np.atleast_1d(np.array(delta))
if delta.size != search_data.shape[1]:
delta = np.append(delta, np.ones(search_data.shape[1]) * delta[0])[: search_data.shape[1]]
results = dict()
results = {}
for ix in range(search_data.shape[0]):
row = np.atleast_1d(search_data[ix])
if tuple(row) in results:
Expand Down Expand Up @@ -547,7 +547,7 @@ def split(self, *args, final="files"):
else:
args = list(args)
xcol = args.pop(0)
data = dict()
data = {}

if isinstance(xcol, index_types):
for val in np.unique(self.column(xcol)):
Expand Down
2 changes: 1 addition & 1 deletion Stoner/core/setas.py
Expand Up @@ -744,7 +744,7 @@ def to_dict(self):
If multiple columns are assigned to the same type, then the column names are
returned as a list. If column headers are duplicated"""
ret = dict()
ret = {}
for k, ch in zip(self._setas, self._unique_headers):
if k != ".":
if k in ret:
Expand Down
2 changes: 1 addition & 1 deletion Stoner/core/utils.py
Expand Up @@ -74,7 +74,7 @@ def add_core(other: Union["DataFile", np.ndarray, List[Numeric], MappingType], n
newdata.data = np.atleast_2d(list(other.values()))
newdata.column_headers = list(other.keys())
else:
order = dict()
order = {}
for k in other:
try:
order[k] = newdata.find_col(k)
Expand Down
14 changes: 7 additions & 7 deletions Stoner/folders/core.py
Expand Up @@ -248,12 +248,12 @@ def __new__(cls, *args, **kargs):
"""
self = super(baseFolder, cls).__new__(cls)
self._debug = kargs.pop("debug", False)
self._object_attrs = dict()
self._object_attrs = {}
self._last_name = 0
self._groups = GroupsDict(base=self)
self._objects = regexpDict()
self._instance = None
self._object_attrs = dict()
self._object_attrs = {}
self._key = None
self._type = metadataObject
self._loader = None
Expand Down Expand Up @@ -306,7 +306,7 @@ def clone(self):
def defaults(self):
"""Build a single list of all of our defaults by iterating over the __mro__, caching the result."""
if getattr(self, "_default_store", None) is None:
self._default_store = dict() # pylint: disable=attribute-defined-outside-init
self._default_store = {} # pylint: disable=attribute-defined-outside-init
for cls in reversed(type(self).__mro__):
if hasattr(cls, "_defaults"):
self._default_store.update(cls._defaults)
Expand Down Expand Up @@ -1061,8 +1061,8 @@ def __walk_groups(self, walker, **kargs):
group = kargs.pop("group", False)
replace_terminal = kargs.pop("replace_terminal", False)
only_terminal = kargs.pop("only_terminal", True)
walker_args = kargs.pop("walker_args", dict())
breadcrumb = kargs.pop("breadcrumb", dict())
walker_args = kargs.pop("walker_args", {})
breadcrumb = kargs.pop("breadcrumb", {})
if len(self.groups) > 0:
ret = []
removeGroups = []
Expand Down Expand Up @@ -1768,8 +1768,8 @@ def walk_groups(self, walker, **kargs):
group = kargs.pop("group", False)
replace_terminal = kargs.pop("replace_terminal", False)
only_terminal = kargs.pop("only_terminal", True)
walker_args = kargs.pop("walker_args", dict())
walker_args = dict() if walker_args is None else walker_args
walker_args = kargs.pop("walker_args", {})
walker_args = {} if walker_args is None else walker_args
return self.__walk_groups(
walker,
group=group,
Expand Down
2 changes: 1 addition & 1 deletion Stoner/folders/mixins.py
Expand Up @@ -96,7 +96,7 @@ class DiskBasedFolderMixin:

_defaults = {
"type": None,
"extra_args": dict(),
"extra_args": {},
"pattern": ["*.*"],
"exclude": ["*.tdms_index"],
"read_means": False,
Expand Down
4 changes: 2 additions & 2 deletions Stoner/folders/utils.py
Expand Up @@ -55,7 +55,7 @@ def scan_dir(root):
def discard_earlier(files):
"""Discard files where a similar named file with !#### exists."""
search = re.compile(r"^(?P<basename>.*)\!(?P<rev>\d+)(?P<ext>\.[^\.]*)$")
dups = dict()
dups = {}
ret = []
for f in files:
match = search.match(f)
Expand Down Expand Up @@ -137,5 +137,5 @@ def removeDisallowedFilenameChars(filename):
Returns:
A filename with non ASCII characters stripped out
"""
validFilenameChars = "-_.() %s%s" % (string.ascii_letters, string.digits)
validFilenameChars = f"-_.() {string.ascii_letters}{string.digits}"
return "".join([c for c in filename if c in validFilenameChars])
2 changes: 1 addition & 1 deletion Stoner/formats/attocube.py
Expand Up @@ -300,7 +300,7 @@ def _read_signal(self, g):
metadata = g.require_group("metadata")
typehints = g.get("typehints", None)
if not isinstance(typehints, h5py.Group):
typehints = dict()
typehints = {}
else:
typehints = typehints.attrs
for i in sorted(metadata.attrs):
Expand Down
4 changes: 2 additions & 2 deletions Stoner/formats/decorators.py
Expand Up @@ -13,9 +13,9 @@

_loaders_by_type = SortedMultivalueDict()
_loaders_by_pattern = SortedMultivalueDict()
_loaders_by_name = dict()
_loaders_by_name = {}
_savers_by_pattern = SortedMultivalueDict()
_savers_by_name = dict()
_savers_by_name = {}

LoadQualifier = Optional[str | Tuple[str, int] | List[str] | List[Tuple[str, int]]]

Expand Down
4 changes: 2 additions & 2 deletions Stoner/formats/instruments.py
Expand Up @@ -235,7 +235,7 @@ def load_rigaku(new_data, filename=None, *args, **kargs):
"""
sh = re.compile(r"^\*([^\s]+)\s+(.*)$") # Regexp to grab the keys
ka = re.compile(r"(.*)\-(\d+)$")
header = dict()
header = {}
i = 0
new_data.filename = filename
with SizedFileManager(new_data.filename, "rb") as (f, end):
Expand Down Expand Up @@ -564,7 +564,7 @@ def load_spc(new_data, filename=None, *args, **kargs):
75 <= new_data._header["fversn"] <= 77
): # This is the multiple XY curves in file flag.
raise StonerLoadError(
"Filetype not implemented yet ! ftflgs={ftflgs}, fversn={fversn}".format(**new_data._header)
f"Filetype not implemented yet ! {new_data._header['ftflgs']=}, {new_data._header['fversn']=}"
)
# Read the xdata and add it to the file.
xdata = _read_spc_xdata(new_data, f)
Expand Down
2 changes: 1 addition & 1 deletion Stoner/formats/maximus.py
Expand Up @@ -320,7 +320,7 @@ def _read_image(self, g):
metadata = g.require_group("metadata")
typehints = g.get("typehints", None)
if not isinstance(typehints, h5py.Group):
typehints = dict()
typehints = {}
else:
typehints = typehints.attrs
for i in sorted(metadata.attrs):
Expand Down
2 changes: 1 addition & 1 deletion Stoner/plot/classes.py
Expand Up @@ -44,7 +44,7 @@ def _trim_kargs(kargs, columns=False, figure=False, annotations=False):
],
"annotations": ["xlabel", "ylabel", "zlabel", "title", "label_props"],
}
classified = dict()
classified = {}
for var, name in zip([columns, figure, annotations], ["columns", "figure", "annotations"]):
if var:
trim = set(args[name]) & set(kargs.keys())
Expand Down
2 changes: 1 addition & 1 deletion Stoner/plot/core.py
Expand Up @@ -470,7 +470,7 @@ def _fix_kargs(self, function=None, defaults=None, otherkargs=None, **kargs):
dictionary of correct arguments, dictionary of all arguments,dictionary of keyword arguments
"""
if defaults is None:
defaults = dict()
defaults = {}
defaults.update(kargs)

pass_fig_kargs = {}
Expand Down
2 changes: 1 addition & 1 deletion Stoner/plot/formats.py
Expand Up @@ -401,7 +401,7 @@ def new_figure(self, figure=False, **kargs):
This is called by PlotMixin to setup a new figure before we do anything."""
plt.style.use("default")
params = dict()
params = {}
self.apply()
if "fig_width_pt" in dir(self):
self.fig_width = self.fig_width_pt * self._inches_per_pt
Expand Down
6 changes: 3 additions & 3 deletions Stoner/tools/classes.py
Expand Up @@ -104,18 +104,18 @@ def subclasses(cls: Optional[type] = None) -> Dict: # pylint: disable=no-self-a

_subclasses = getattr(cls, "_subclasses", None)
if _subclasses is None:
_subclasses = dict()
_subclasses = {}
tmp = itersubclasses(cls)
if len(_subclasses) < 1 or _subclasses[0] != len(tmp): # Rebuild index
tmp = {
x: (getattr(x, "priority", 256), x.__name__)
for x in sorted(tmp, key=lambda c: (getattr(c, "priority", 256), getattr(c, "__name__", "None")))
}
tmp = {v[1]: k for k, v in tmp.items()}
ret = dict()
ret = {}
ret[cls.__name__] = cls
ret.update(tmp)
_subclasses = dict()
_subclasses = {}
_subclasses = (len(tmp), ret)
else:
ret = dict(_subclasses[1])
Expand Down
2 changes: 1 addition & 1 deletion Stoner/tools/formatting.py
Expand Up @@ -339,4 +339,4 @@ def ordinal(value: int) -> str:
else:
suffix = ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"][last_digit]

return "{}{}".format(value, suffix)
return f"{value}{suffix}"
2 changes: 1 addition & 1 deletion Stoner/tools/widgets.py
Expand Up @@ -21,7 +21,7 @@ class App:

"""Mock App that raises an error when you try to call openDialog on it."""

modes: Dict = dict()
modes: Dict = {}

def openDialog(
self,
Expand Down
30 changes: 15 additions & 15 deletions tests/Stoner/mixedmetatest.dat
@@ -1,15 +1,15 @@
TDI Format 1.5 1 2 3 4
Stoner.class{String}=Data 0 1 2 3
t0{Boolean}=True 4 5 6 7
t1{I32}=1 8 9 10 11
t10{List}=[1, (1, 2), 'abc']
t11{List}=[[[1]]]
t12{Void}=None
t2{Double Float}=0.2
t3{Cluster (I32,String)}={'a': 1, 'b': 'abc'}
t4{Cluster (I32,I32)}=(1, 2)
t5{1D Array (Invalid Type)}=array([0, 1, 2])
t6{List}=[1, 2, 3]
t7{String}=abc
t8{String}=\\abc\cde
t9{Double Float}=1e-20
TDI Format 1.5 1 2 3 4
Stoner.class{String}=Data 0 1 2 3
t0{Boolean}=True 4 5 6 7
t1{I32}=1 8 9 10 11
t10{List}=[1, (1, 2), 'abc']
t11{List}=[[[1]]]
t12{Void}=None
t2{Double Float}=0.2
t3{Cluster (I32,String)}={'a': 1, 'b': 'abc'}
t4{Cluster (I32,I32)}=(1, 2)
t5{1D Array (Invalid Type)}=array([0, 1, 2])
t6{List}=[1, 2, 3]
t7{String}=abc
t8{String}=\\abc\cde
t9{Double Float}=1e-20

0 comments on commit ee19dbb

Please sign in to comment.