Skip to content

Commit 5cc93fe

Browse files
committed
use dict.get over explicit key in dict check
1 parent 494ab60 commit 5cc93fe

File tree

11 files changed

+46
-49
lines changed

11 files changed

+46
-49
lines changed

pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1864,7 +1864,7 @@ def from_dict(cls, dd):
18641864
delta_cn_weight_estimators={
18651865
int(dcn): dcn_estimator for dcn, dcn_estimator in dd["delta_cn_weight_estimators"].items()
18661866
}
1867-
if ("delta_cn_weight_estimators" in dd and dd["delta_cn_weight_estimators"] is not None)
1867+
if dd.get("delta_cn_weight_estimators") is not None
18681868
else None,
18691869
symmetry_measure_type=dd["symmetry_measure_type"],
18701870
)

pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -631,9 +631,11 @@ def from_dict(cls, dct):
631631
if dct["_algorithms"] is not None
632632
else None,
633633
equivalent_indices=dct.get("equivalent_indices"),
634-
neighbors_sets_hints=[cls.NeighborsSetsHints.from_dict(nbshd) for nbshd in dct["neighbors_sets_hints"]]
635-
if ("neighbors_sets_hints" in dct and dct["neighbors_sets_hints"] is not None)
636-
else None,
634+
neighbors_sets_hints=[
635+
cls.NeighborsSetsHints.from_dict(nb_sets_hints)
636+
for nb_sets_hints in dct.get("neighbors_sets_hints") or []
637+
]
638+
or None,
637639
)
638640

639641
def __str__(self):

pymatgen/analysis/chemenv/utils/defs_utils.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -85,20 +85,20 @@ def check_condition(self, condition, structure: Structure, parameters):
8585
if condition == self.NO_E2SEB:
8686
ii = parameters["site_index"]
8787
jj = parameters["neighbor_index"]
88-
elmts_ii = [sp.symbol for sp in structure[ii].species]
89-
elmts_jj = [sp.symbol for sp in structure[jj].species]
90-
return len(set(elmts_ii) & set(elmts_jj)) == 0
88+
elems_ii = [sp.symbol for sp in structure[ii].species]
89+
elems_jj = [sp.symbol for sp in structure[jj].species]
90+
return len(set(elems_ii) & set(elems_jj)) == 0
9191
if condition == self.ONLY_ACB_AND_NO_E2SEB:
9292
valences = parameters["valences"]
9393
ii = parameters["site_index"]
9494
jj = parameters["neighbor_index"]
95-
elmts_ii = [sp.symbol for sp in structure[ii].species]
96-
elmts_jj = [sp.symbol for sp in structure[jj].species]
97-
return len(set(elmts_ii) & set(elmts_jj)) == 0 and is_anion_cation_bond(valences, ii, jj)
95+
elems_ii = [sp.symbol for sp in structure[ii].species]
96+
elems_jj = [sp.symbol for sp in structure[jj].species]
97+
return len(set(elems_ii) & set(elems_jj)) == 0 and is_anion_cation_bond(valences, ii, jj)
9898
if condition == self.ONLY_E2OB:
9999
ii = parameters["site_index"]
100100
jj = parameters["neighbor_index"]
101-
elmts_ii = [sp.symbol for sp in structure[ii].species]
102-
elmts_jj = [sp.symbol for sp in structure[jj].species]
103-
return ("O" in elmts_jj and "O" not in elmts_ii) or ("O" in elmts_ii and "O" not in elmts_jj)
101+
elems_ii = [sp.symbol for sp in structure[ii].species]
102+
elems_jj = [sp.symbol for sp in structure[jj].species]
103+
return ("O" in elems_jj and "O" not in elems_ii) or ("O" in elems_ii and "O" not in elems_jj)
104104
return None

pymatgen/analysis/chemenv/utils/graph_utils.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -194,14 +194,12 @@ def validate(self, check_strict_ordering=False):
194194
def order(self, raise_on_fail=True):
195195
"""Orders the SimpleGraphCycle.
196196
197-
The ordering is performed such that the first node is the "lowest" one
198-
and the second node is the lowest one of the two neighbor nodes of the
199-
first node. If raise_on_fail is set to True a RuntimeError will be
200-
raised if the ordering fails.
197+
The ordering is performed such that the first node is the "lowest" one and the
198+
second node is the lowest one of the two neighbor nodes of the first node. If
199+
raise_on_fail is set to True a RuntimeError will be raised if the ordering fails.
201200
202-
:param raise_on_fail: If set to True, will raise a RuntimeError if the
203-
ordering fails.
204-
:return: None
201+
Args:
202+
raise_on_fail (bool): If set to True, will raise a RuntimeError if the ordering fails.
205203
"""
206204
# always validate the cycle if it needs to be ordered
207205
# also validates that the nodes can be strictly ordered

pymatgen/io/abinit/pseudos.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -262,14 +262,14 @@ def as_dict(self, **kwargs):
262262
}
263263

264264
@classmethod
265-
def from_dict(cls, d):
265+
def from_dict(cls, dct):
266266
"""Build instance from dictionary (MSONable protocol)."""
267-
new = cls.from_file(d["filepath"])
267+
new = cls.from_file(dct["filepath"])
268268

269269
# Consistency test based on md5
270-
if "md5" in d and d["md5"] != new.md5:
270+
if "md5" in dct and dct["md5"] != new.md5:
271271
raise ValueError(
272-
f"The md5 found in file does not agree with the one in dict\nReceived {d['md5']}\nComputed {new.md5}"
272+
f"The md5 found in file does not agree with the one in dict\nReceived {dct['md5']}\nComputed {new.md5}"
273273
)
274274

275275
return new

pymatgen/io/cp2k/outputs.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,8 +212,8 @@ def is_metal(self) -> bool:
212212
@property
213213
def is_hubbard(self) -> bool:
214214
"""Returns True if hubbard +U correction was used."""
215-
for v in self.data.get("atomic_kind_info", {}).values():
216-
if "DFT_PLUS_U" in v and v.get("DFT_PLUS_U").get("U_MINUS_J") > 0:
215+
for val in self.data.get("atomic_kind_info", {}).values():
216+
if val.get("DFT_PLUS_U", {}).get("U_MINUS_J", 0) > 0:
217217
return True
218218
return False
219219

pymatgen/io/lmto.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -250,45 +250,44 @@ def from_str(cls, data, sigfigs=8):
250250
return LMTOCtrl.from_dict(structure_tokens)
251251

252252
@classmethod
253-
def from_dict(cls, d):
253+
def from_dict(cls, dct):
254254
"""
255255
Creates a CTRL file object from a dictionary. The dictionary
256256
must contain the items "ALAT", PLAT" and "SITE".
257257
258258
Valid dictionary items are:
259259
ALAT: the a-lattice parameter
260260
PLAT: (3x3) array for the lattice vectors
261-
SITE: list of dictionaries: {'ATOM': class label,
262-
'POS': (3x1) array of fractional
263-
coordinates}
261+
SITE: list of dictionaries: {'ATOM': class label, 'POS': (3x1) array of fractional coordinates}
264262
CLASS (optional): list of unique atom labels as str
265263
SPCGRP (optional): space group symbol (str) or number (int)
266264
HEADER (optional): HEADER text as a str
267265
VERS (optional): LMTO version as a str
268266
269267
Args:
270-
d: The CTRL file as a dictionary.
268+
dct: The CTRL file as a dictionary.
271269
272270
Returns:
273271
An LMTOCtrl object.
274272
"""
275-
for cat in ["HEADER", "VERS"]:
276-
if cat not in d:
277-
d[cat] = None
278-
alat = d["ALAT"] * bohr_to_angstrom
279-
plat = d["PLAT"] * alat
273+
dct.setdefault("HEADER", None)
274+
dct.setdefault("VERS", None)
275+
alat = dct["ALAT"] * bohr_to_angstrom
276+
plat = dct["PLAT"] * alat
280277
species = []
281278
positions = []
282-
for site in d["SITE"]:
279+
for site in dct["SITE"]:
283280
species.append(re.split("[0-9*]", site["ATOM"])[0])
284281
positions.append(site["POS"] * alat)
285282

286283
# Only check if the structure is to be generated from the space
287284
# group if the number of sites is the same as the number of classes.
288285
# If lattice and the spacegroup don't match, assume it's primitive.
289-
if "CLASS" in d and "SPCGRP" in d and len(d["SITE"]) == len(d["CLASS"]):
286+
if "CLASS" in dct and "SPCGRP" in dct and len(dct["SITE"]) == len(dct["CLASS"]):
290287
try:
291-
structure = Structure.from_spacegroup(d["SPCGRP"], plat, species, positions, coords_are_cartesian=True)
288+
structure = Structure.from_spacegroup(
289+
dct["SPCGRP"], plat, species, positions, coords_are_cartesian=True
290+
)
292291
except ValueError:
293292
structure = Structure(
294293
plat,
@@ -300,7 +299,7 @@ def from_dict(cls, d):
300299
else:
301300
structure = Structure(plat, species, positions, coords_are_cartesian=True, to_unit_cell=True)
302301

303-
return cls(structure, header=d["HEADER"], version=d["VERS"])
302+
return cls(structure, header=dct["HEADER"], version=dct["VERS"])
304303

305304

306305
class LMTOCopl:

pymatgen/io/vasp/outputs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -607,7 +607,7 @@ def converged_electronic(self):
607607
"""
608608
final_esteps = self.ionic_steps[-1]["electronic_steps"] if self.incar not in ["CHI"] else 0
609609
# In a response function run there is no ionic steps, there is no scf step
610-
if "LEPSILON" in self.incar and self.incar["LEPSILON"]:
610+
if self.incar.get("LEPSILON"):
611611
i = 1
612612
to_check = {"e_wo_entrp", "e_fr_energy", "e_0_energy"}
613613
while set(final_esteps[i]) == to_check:

pymatgen/io/vasp/sets.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -763,7 +763,7 @@ def calculate_ng(self, max_prime_factor: int = 7, must_inc_2: bool = True) -> tu
763763
# TODO Only do this for VASP 6 for now. Older version require more advanced logic
764764

765765
# get the ENCUT val
766-
if "ENCUT" in self.incar and self.incar["ENCUT"] > 0:
766+
if self.incar.get("ENCUT", 0) > 0:
767767
encut = self.incar["ENCUT"]
768768
else:
769769
encut = max(i_species.enmax for i_species in self.get_vasp_input()["POTCAR"])

pymatgen/io/vasp/tests/test_sets.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -725,17 +725,15 @@ def test_standardize_structure(self):
725725

726726
def test_write_input_zipped(self):
727727
vis = MPStaticSet(self.get_structure("Si"))
728-
vis.write_input(output_dir=".", potcar_spec=True, zip_output=True)
728+
vis.write_input(output_dir=self.tmp_path, potcar_spec=True, zip_output=True)
729729

730-
assert os.path.isfile("MPStaticSet.zip")
731-
with ZipFile("MPStaticSet.zip", "r") as zip:
730+
assert os.path.isfile(f"{self.tmp_path}/MPStaticSet.zip")
731+
with ZipFile(f"{self.tmp_path}/MPStaticSet.zip", "r") as zip:
732732
contents = zip.namelist()
733733
assert set(contents).issuperset({"INCAR", "POSCAR", "POTCAR.spec", "KPOINTS"})
734734
spec = zip.open("POTCAR.spec", "r").read().decode()
735735
assert spec == "Si"
736736

737-
os.remove("MPStaticSet.zip")
738-
739737
def test_grid_size_from_struct(self):
740738
# TODO grab a bunch_of_calculations store as a list of tuples
741739
# (structure, ngx, ..., ngxf, ...) where all the grid size values are generated by vasp

0 commit comments

Comments
 (0)