Coverage for ase/utils/__init__.py: 82.08%

413 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import errno 

2import functools 

3import io 

4import os 

5import pickle 

6import re 

7import string 

8import sys 

9import time 

10import warnings 

11from collections.abc import Callable 

12from contextlib import ExitStack, contextmanager 

13from importlib import import_module 

14from math import atan2, cos, degrees, gcd, radians, sin 

15from pathlib import Path, PurePath 

16 

17import numpy as np 

18 

19from ase.formula import formula_hill, formula_metal 

20 

21__all__ = [ 

22 'basestring', 

23 'import_module', 

24 'seterr', 

25 'plural', 

26 'devnull', 

27 'gcd', 

28 'convert_string_to_fd', 

29 'Lock', 

30 'opencew', 

31 'OpenLock', 

32 'rotate', 

33 'irotate', 

34 'pbc2pbc', 

35 'givens', 

36 'hsv2rgb', 

37 'hsv', 

38 'pickleload', 

39 'reader', 

40 'formula_hill', 

41 'formula_metal', 

42 'PurePath', 

43 'xwopen', 

44 'tokenize_version', 

45 'get_python_package_path_description', 

46] 

47 

48 

49def tokenize_version(version_string: str): 

50 """Parse version string into a tuple for version comparisons. 

51 

52 Usage: tokenize_version('3.8') < tokenize_version('3.8.1'). 

53 """ 

54 tokens = [] 

55 for component in version_string.split('.'): 

56 match = re.match(r'(\d*)(.*)', component) 

57 assert match is not None, f'Cannot parse component {component}' 

58 number_str, tail = match.group(1, 2) 

59 try: 

60 number = int(number_str) 

61 except ValueError: 

62 number = -1 

63 tokens += [number, tail] 

64 return tuple(tokens) 

65 

66 

67# Python 2+3 compatibility stuff (let's try to remove these things): 

68basestring = str 

69pickleload = functools.partial(pickle.load, encoding='bytes') 

70 

71 

72def deprecate_positionals(maxargs: int): 

73 """Decorate a function to warn when too many positional arguments are used. 

74 

75 .. versionadded:: 3.30.0 

76 

77 Parameters 

78 ---------- 

79 maxargs : int 

80 Maximum number of positional arguments allowed without a warning. 

81 

82 Returns 

83 ------- 

84 Callable 

85 A decorator that emits a FutureWarning when the decorated function 

86 is called with more than `maxargs` positional arguments. 

87 """ 

88 

89 def decorator(func): 

90 @functools.wraps(func) 

91 def wrapper(*args, **kwargs): 

92 if len(args) > maxargs: 

93 warnings.warn( 

94 f'Please do not call {func.__qualname__} with more than ' 

95 f'{maxargs} positional arguments. Use keywords instead.', 

96 FutureWarning, 

97 ) 

98 return func(*args, **kwargs) 

99 

100 return wrapper 

101 

102 return decorator 

103 

104 

105def deprecated( 

106 message: str | Warning, 

107 category: type[Warning] = FutureWarning, 

108 callback: Callable[[list, dict], bool] = lambda args, kwargs: True, 

109): 

110 """Return a decorator deprecating a function. 

111 

112 Parameters 

113 ---------- 

114 message : str or Warning 

115 The message to be emitted. If ``message`` is a Warning, then 

116 ``category`` is ignored and ``message.__class__`` will be used. 

117 category : type[Warning], default=FutureWarning 

118 The type of warning to be emitted. If ``message`` is a ``Warning`` 

119 instance, then ``category`` will be ignored and ``message.__class__`` 

120 will be used. 

121 callback : Callable[[list, dict], bool], default=lambda args, kwargs: True 

122 A callable that determines if the warning should be emitted and handles 

123 any processing prior to calling the deprecated function. The callable 

124 will receive two arguments, a list and a dictionary. The list will 

125 contain the positional arguments that the deprecated function was 

126 called with at runtime while the dictionary will contain the keyword 

127 arguments. The callable *must* return ``True`` if the warning is to be 

128 emitted and ``False`` otherwise. The list and dictionary will be 

129 unpacked into the positional and keyword arguments, respectively, used 

130 to call the deprecated function. 

131 

132 Returns 

133 ------- 

134 deprecated_decorator : Callable 

135 A decorator for deprecated functions that can be used to conditionally 

136 emit deprecation warnings and/or pre-process the arguments of a 

137 deprecated function. 

138 

139 Example 

140 ------- 

141 >>> # Inspect & replace a keyword parameter passed to a deprecated function 

142 >>> from typing import Any, Callable 

143 >>> import warnings 

144 >>> from ase.utils import deprecated 

145 

146 >>> def alias_callback_factory(kwarg: str, alias: str) -> Callable: 

147 ... def _replace_arg(_: list, kwargs: dict[str, Any]) -> bool: 

148 ... kwargs[kwarg] = kwargs[alias] 

149 ... del kwargs[alias] 

150 ... return True 

151 ... return _replace_arg 

152 

153 >>> MESSAGE = ("Calling this function with `atoms` is deprecated. " 

154 ... "Use `optimizable` instead.") 

155 >>> @deprecated( 

156 ... MESSAGE, 

157 ... category=DeprecationWarning, 

158 ... callback=alias_callback_factory("optimizable", "atoms") 

159 ... ) 

160 ... def function(*, atoms=None, optimizable=None): 

161 ... ''' 

162 ... .. deprecated:: 3.23.0 

163 ... Calling this function with ``atoms`` is deprecated. 

164 ... Use ``optimizable`` instead. 

165 ... ''' 

166 ... print(f"atoms: {atoms}") 

167 ... print(f"optimizable: {optimizable}") 

168 

169 >>> with warnings.catch_warnings(record=True) as w: 

170 ... warnings.simplefilter("always") 

171 ... function(atoms="atoms") 

172 atoms: None 

173 optimizable: atoms 

174 

175 >>> w[-1].category == DeprecationWarning 

176 True 

177 """ 

178 

179 def deprecated_decorator(func): 

180 @functools.wraps(func) 

181 def deprecated_function(*args, **kwargs): 

182 _args = list(args) 

183 if callback(_args, kwargs): 

184 warnings.warn(message, category=category, stacklevel=2) 

185 

186 return func(*_args, **kwargs) 

187 

188 return deprecated_function 

189 

190 return deprecated_decorator 

191 

192 

193@contextmanager 

194def seterr(**kwargs): 

195 """Set how floating-point errors are handled. 

196 

197 See np.seterr() for more details. 

198 """ 

199 old = np.seterr(**kwargs) 

200 try: 

201 yield 

202 finally: 

203 np.seterr(**old) 

204 

205 

206def plural(n, word): 

207 """Use plural for n!=1. 

208 

209 >>> from ase.utils import plural 

210 

211 >>> plural(0, 'egg'), plural(1, 'egg'), plural(2, 'egg') 

212 ('0 eggs', '1 egg', '2 eggs') 

213 """ 

214 if n == 1: 

215 return '1 ' + word 

216 return '%d %ss' % (n, word) 

217 

218 

219class DevNull: 

220 encoding = 'UTF-8' 

221 closed = False 

222 

223 _use_os_devnull = deprecated( 

224 'use open(os.devnull) instead', DeprecationWarning 

225 ) 

226 # Deprecated for ase-3.21.0. Change to futurewarning later on. 

227 

228 @_use_os_devnull 

229 def write(self, string): 

230 pass 

231 

232 @_use_os_devnull 

233 def flush(self): 

234 pass 

235 

236 @_use_os_devnull 

237 def seek(self, offset, whence=0): 

238 return 0 

239 

240 @_use_os_devnull 

241 def tell(self): 

242 return 0 

243 

244 @_use_os_devnull 

245 def close(self): 

246 pass 

247 

248 @_use_os_devnull 

249 def isatty(self): 

250 return False 

251 

252 @_use_os_devnull 

253 def read(self, n=-1): 

254 return '' 

255 

256 

257devnull = DevNull() 

258 

259 

260@deprecated( 

261 'convert_string_to_fd does not facilitate proper resource ' 

262 'management. ' 

263 'Please use e.g. ase.utils.IOContext class instead.' 

264) 

265def convert_string_to_fd(name, world=None): 

266 """Create a file-descriptor for text output. 

267 

268 Will open a file for writing with given name. Use None for no output and 

269 '-' for sys.stdout. 

270 

271 .. deprecated:: 3.22.1 

272 Please use e.g. :class:`ase.utils.IOContext` class instead. 

273 """ 

274 if world is None: 

275 from ase.parallel import world 

276 if name is None or world.rank != 0: 

277 return open(os.devnull, 'w') 

278 if name == '-': 

279 return sys.stdout 

280 if isinstance(name, (str, PurePath)): 

281 return open(str(name), 'w') # str for py3.5 pathlib 

282 return name # we assume name is already a file-descriptor 

283 

284 

285# Only Windows has O_BINARY: 

286CEW_FLAGS = os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, 'O_BINARY', 0) 

287 

288 

289@contextmanager 

290def xwopen(filename, world=None): 

291 """Create and open filename exclusively for writing. 

292 

293 If master cpu gets exclusive write access to filename, a file 

294 descriptor is returned (a dummy file descriptor is returned on the 

295 slaves). If the master cpu does not get write access, None is 

296 returned on all processors.""" 

297 

298 fd = opencew(filename, world) 

299 try: 

300 yield fd 

301 finally: 

302 if fd is not None: 

303 fd.close() 

304 

305 

306# @deprecated('use "with xwopen(...) as fd: ..." to prevent resource leak') 

307def opencew(filename, world=None): 

308 return _opencew(filename, world) 

309 

310 

311def _opencew(filename, world=None): 

312 import ase.parallel as parallel 

313 

314 if world is None: 

315 world = parallel.world 

316 

317 closelater = [] 

318 

319 def opener(file, flags): 

320 return os.open(file, flags | CEW_FLAGS) 

321 

322 try: 

323 error = 0 

324 if world.rank == 0: 

325 try: 

326 fd = open(filename, 'wb', opener=opener) 

327 except OSError as ex: 

328 error = ex.errno 

329 else: 

330 closelater.append(fd) 

331 else: 

332 fd = open(os.devnull, 'wb') 

333 closelater.append(fd) 

334 

335 # Synchronize: 

336 error = world.sum_scalar(error) 

337 if error == errno.EEXIST: 

338 return None 

339 if error: 

340 raise OSError(error, 'Error', filename) 

341 

342 return fd 

343 except BaseException: 

344 for fd in closelater: 

345 fd.close() 

346 raise 

347 

348 

349def opencew_text(*args, **kwargs): 

350 fd = opencew(*args, **kwargs) 

351 if fd is None: 

352 return None 

353 return io.TextIOWrapper(fd) 

354 

355 

356class Lock: 

357 def __init__(self, name='lock', world=None, timeout=float('inf')): 

358 self.name = str(name) 

359 self.timeout = timeout 

360 if world is None: 

361 from ase.parallel import world 

362 self.world = world 

363 

364 def acquire(self): 

365 dt = 0.2 

366 t1 = time.time() 

367 while True: 

368 fd = opencew(self.name, self.world) 

369 if fd is not None: 

370 self.fd = fd 

371 break 

372 time_left = self.timeout - (time.time() - t1) 

373 if time_left <= 0: 

374 raise TimeoutError 

375 time.sleep(min(dt, time_left)) 

376 dt *= 2 

377 

378 def release(self): 

379 self.world.barrier() 

380 # Important to close fd before deleting file on windows 

381 # as a WinError would otherwise be raised. 

382 self.fd.close() 

383 if self.world.rank == 0: 

384 os.remove(self.name) 

385 self.world.barrier() 

386 

387 def __enter__(self): 

388 self.acquire() 

389 

390 def __exit__(self, type, value, tb): 

391 self.release() 

392 

393 

394class OpenLock: 

395 def acquire(self): 

396 pass 

397 

398 def release(self): 

399 pass 

400 

401 def __enter__(self): 

402 pass 

403 

404 def __exit__(self, type, value, tb): 

405 pass 

406 

407 

408def search_current_git_hash(arg, world=None): 

409 """Search for .git directory and current git commit hash. 

410 

411 Parameters 

412 ---------- 

413 

414 arg: str (directory path) or python module 

415 .git directory is searched from the parent directory of 

416 the given directory or module. 

417 """ 

418 if world is None: 

419 from ase.parallel import world 

420 if world.rank != 0: 

421 return None 

422 

423 # Check argument 

424 if isinstance(arg, str): 

425 # Directory path 

426 dpath = arg 

427 else: 

428 # Assume arg is module 

429 dpath = os.path.dirname(arg.__file__) 

430 # dpath = os.path.abspath(dpath) 

431 # in case this is just symlinked into $PYTHONPATH 

432 dpath = os.path.realpath(dpath) 

433 dpath = os.path.dirname(dpath) # Go to the parent directory 

434 git_dpath = os.path.join(dpath, '.git') 

435 if not os.path.isdir(git_dpath): 

436 # Replace this 'if' with a loop if you want to check 

437 # further parent directories 

438 return None 

439 HEAD_file = os.path.join(git_dpath, 'HEAD') 

440 if not os.path.isfile(HEAD_file): 

441 return None 

442 with open(HEAD_file) as fd: 

443 line = fd.readline().strip() 

444 if line.startswith('ref: '): 

445 ref = line[5:] 

446 ref_file = os.path.join(git_dpath, ref) 

447 else: 

448 # Assuming detached HEAD state 

449 ref_file = HEAD_file 

450 if not os.path.isfile(ref_file): 

451 return None 

452 with open(ref_file) as fd: 

453 line = fd.readline().strip() 

454 if all(c in string.hexdigits for c in line): 

455 return line 

456 return None 

457 

458 

459def rotate(rotations, rotation=np.identity(3)): 

460 """Convert string of format '50x,-10y,120z' to a rotation matrix. 

461 

462 Note that the order of rotation matters, i.e. '50x,40z' is different 

463 from '40z,50x'. 

464 """ 

465 

466 if rotations == '': 

467 return rotation.copy() 

468 

469 for i, a in [ 

470 ('xyz'.index(s[-1]), radians(float(s[:-1]))) 

471 for s in rotations.split(',') 

472 ]: 

473 s = sin(a) 

474 c = cos(a) 

475 if i == 0: 

476 rotation = np.dot(rotation, [(1, 0, 0), (0, c, s), (0, -s, c)]) 

477 elif i == 1: 

478 rotation = np.dot(rotation, [(c, 0, -s), (0, 1, 0), (s, 0, c)]) 

479 else: 

480 rotation = np.dot(rotation, [(c, s, 0), (-s, c, 0), (0, 0, 1)]) 

481 return rotation 

482 

483 

484def givens(a, b): 

485 """Solve the equation system:: 

486 

487 [ c s] [a] [r] 

488 [ ] . [ ] = [ ] 

489 [-s c] [b] [0] 

490 """ 

491 sgn = np.sign 

492 if b == 0: 

493 c = sgn(a) 

494 s = 0 

495 r = abs(a) 

496 elif abs(b) >= abs(a): 

497 cot = a / b 

498 u = sgn(b) * (1 + cot**2) ** 0.5 

499 s = 1.0 / u 

500 c = s * cot 

501 r = b * u 

502 else: 

503 tan = b / a 

504 u = sgn(a) * (1 + tan**2) ** 0.5 

505 c = 1.0 / u 

506 s = c * tan 

507 r = a * u 

508 return c, s, r 

509 

510 

511def irotate(rotation, initial=np.identity(3)): 

512 """Determine x, y, z rotation angles from rotation matrix.""" 

513 a = np.dot(initial, rotation) 

514 cx, sx, rx = givens(a[2, 2], a[1, 2]) 

515 cy, sy, _ry = givens(rx, a[0, 2]) 

516 cz, sz, _rz = givens( 

517 cx * a[1, 1] - sx * a[2, 1], 

518 cy * a[0, 1] - sy * (sx * a[1, 1] + cx * a[2, 1]), 

519 ) 

520 x = degrees(atan2(sx, cx)) 

521 y = degrees(atan2(-sy, cy)) 

522 z = degrees(atan2(sz, cz)) 

523 return x, y, z 

524 

525 

526def pbc2pbc(pbc): 

527 newpbc = np.empty(3, bool) 

528 newpbc[:] = pbc 

529 return newpbc 

530 

531 

532def string2index(stridx: str) -> int | slice | str: 

533 """Convert index string to either int or slice""" 

534 if ':' not in stridx: 

535 # may contain database accessor 

536 try: 

537 return int(stridx) 

538 except ValueError: 

539 return stridx 

540 i = [None if s == '' else int(s) for s in stridx.split(':')] 

541 return slice(*i) 

542 

543 

544def hsv2rgb(h, s, v): 

545 """http://en.wikipedia.org/wiki/HSL_and_HSV 

546 

547 h (hue) in [0, 360[ 

548 s (saturation) in [0, 1] 

549 v (value) in [0, 1] 

550 

551 return rgb in range [0, 1] 

552 """ 

553 if v == 0: 

554 return 0, 0, 0 

555 if s == 0: 

556 return v, v, v 

557 

558 i, f = divmod(h / 60.0, 1) 

559 p = v * (1 - s) 

560 q = v * (1 - s * f) 

561 t = v * (1 - s * (1 - f)) 

562 

563 if i == 0: 

564 return v, t, p 

565 elif i == 1: 

566 return q, v, p 

567 elif i == 2: 

568 return p, v, t 

569 elif i == 3: 

570 return p, q, v 

571 elif i == 4: 

572 return t, p, v 

573 elif i == 5: 

574 return v, p, q 

575 else: 

576 raise RuntimeError('h must be in [0, 360]') 

577 

578 

579def hsv(array, s=0.9, v=0.9): 

580 array = (array + array.min()) * 359.0 / (array.max() - array.min()) 

581 result = np.empty((len(array.flat), 3)) 

582 for rgb, h in zip(result, array.flat): 

583 rgb[:] = hsv2rgb(h, s, v) 

584 return np.reshape(result, array.shape + (3,)) 

585 

586 

587# This code does the same, but requires pylab 

588# def cmap(array, name='hsv'): 

589# import pylab 

590# a = (array + array.min()) / array.ptp() 

591# rgba = getattr(pylab.cm, name)(a) 

592# return rgba[:-1] # return rgb only (not alpha) 

593 

594 

595def longsum(x): 

596 """128-bit floating point sum.""" 

597 return float(np.asarray(x, dtype=np.longdouble).sum()) 

598 

599 

600@contextmanager 

601def workdir(path, mkdir=False): 

602 """Temporarily change, and optionally create, working directory.""" 

603 path = Path(path) 

604 if mkdir: 

605 path.mkdir(parents=True, exist_ok=True) 

606 

607 olddir = os.getcwd() 

608 os.chdir(path) 

609 try: 

610 yield # Yield the Path or dirname maybe? 

611 finally: 

612 os.chdir(olddir) 

613 

614 

615class iofunction: 

616 """Decorate func so it accepts either str or file. 

617 

618 (Won't work on functions that return a generator.)""" 

619 

620 def __init__(self, mode): 

621 self.mode = mode 

622 

623 def __call__(self, func): 

624 @functools.wraps(func) 

625 def iofunc(file, *args, **kwargs): 

626 openandclose = isinstance(file, (str, PurePath)) 

627 fd = None 

628 try: 

629 if openandclose: 

630 fd = open(str(file), self.mode) 

631 else: 

632 fd = file 

633 obj = func(fd, *args, **kwargs) 

634 return obj 

635 finally: 

636 if openandclose and fd is not None: 

637 # fd may be None if open() failed 

638 fd.close() 

639 

640 return iofunc 

641 

642 

643def writer(func): 

644 return iofunction('w')(func) 

645 

646 

647def reader(func): 

648 return iofunction('r')(func) 

649 

650 

651# The next two functions are for hotplugging into a JSONable class 

652# using the jsonable decorator. We are supposed to have this kind of stuff 

653# in ase.io.jsonio, but we'd rather import them from a 'basic' module 

654# like ase/utils than one which triggers a lot of extra (cyclic) imports. 

655 

656 

657def write_json(self, fd): 

658 """Write to JSON file.""" 

659 from ase.io.jsonio import write_json as _write_json 

660 

661 _write_json(fd, self) 

662 

663 

664@classmethod # type: ignore[misc] 

665def read_json(cls, fd): 

666 """Read new instance from JSON file.""" 

667 from ase.io.jsonio import read_json as _read_json 

668 

669 obj = _read_json(fd) 

670 assert isinstance(obj, cls) 

671 return obj 

672 

673 

674def jsonable(name): 

675 """Decorator for facilitating JSON I/O with a class. 

676 

677 Pokes JSON-based read and write functions into the class. 

678 

679 In order to write an object to JSON, it needs to be a known simple type 

680 (such as ndarray, float, ...) or implement todict(). If the class 

681 defines a string called ase_objtype, the decoder will want to convert 

682 the object back into its original type when reading.""" 

683 

684 def jsonableclass(cls): 

685 cls.ase_objtype = name 

686 if not hasattr(cls, 'todict'): 

687 raise TypeError('Class must implement todict()') 

688 

689 # We may want the write and read to be optional. 

690 # E.g. a calculator might want to be JSONable, but not 

691 # that .write() produces a JSON file. 

692 # 

693 # This is mostly for 'lightweight' object IO. 

694 cls.write = write_json 

695 cls.read = read_json 

696 return cls 

697 

698 return jsonableclass 

699 

700 

701class ExperimentalFeatureWarning(Warning): 

702 pass 

703 

704 

705def experimental(func): 

706 """Decorator for functions not ready for production use.""" 

707 

708 @functools.wraps(func) 

709 def expfunc(*args, **kwargs): 

710 warnings.warn( 

711 'This function may change or misbehave: {}()'.format( 

712 func.__qualname__ 

713 ), 

714 ExperimentalFeatureWarning, 

715 ) 

716 return func(*args, **kwargs) 

717 

718 return expfunc 

719 

720 

721@deprecated('use functools.cached_property instead') 

722def lazymethod(meth): 

723 """Decorator for lazy evaluation and caching of data. 

724 

725 Example:: 

726 

727 class MyClass: 

728 

729 @lazymethod 

730 def thing(self): 

731 return expensive_calculation() 

732 

733 The method body is only executed first time thing() is called, and 

734 its return value is stored. Subsequent calls return the cached 

735 value. 

736 

737 .. deprecated:: 3.25.0 

738 """ 

739 name = meth.__name__ 

740 

741 @functools.wraps(meth) 

742 def getter(self): 

743 try: 

744 cache = self._lazy_cache 

745 except AttributeError: 

746 cache = self._lazy_cache = {} 

747 

748 if name not in cache: 

749 cache[name] = meth(self) 

750 return cache[name] 

751 

752 return getter 

753 

754 

755def atoms_to_spglib_cell(atoms): 

756 """Convert atoms into data suitable for calling spglib.""" 

757 return ( 

758 atoms.get_cell(), 

759 atoms.get_scaled_positions(), 

760 atoms.get_atomic_numbers(), 

761 ) 

762 

763 

764def warn_legacy(feature_name): 

765 warnings.warn( 

766 f'The {feature_name} feature is untested and ASE developers do not ' 

767 'know whether it works or how to use it. Please rehabilitate it ' 

768 '(by writing unittests) or it may be removed.', 

769 FutureWarning, 

770 ) 

771 

772 

773@deprecated('use functools.cached_property instead') 

774def lazyproperty(meth): 

775 """Decorator like lazymethod, but making item available as a property. 

776 

777 .. deprecated:: 3.25.0 

778 """ 

779 return property(lazymethod(meth)) 

780 

781 

782class _DelExitStack(ExitStack): 

783 # We don't want IOContext itself to implement __del__, since IOContext 

784 # might be subclassed, and we don't want __del__ on objects that we 

785 # don't fully control. Therefore we make a little custom class 

786 # that nobody else refers to, and that has the __del__. 

787 def __del__(self): 

788 self.close() 

789 

790 

791class IOContext: 

792 @functools.cached_property 

793 def _exitstack(self): 

794 return _DelExitStack() 

795 

796 def __enter__(self): 

797 return self 

798 

799 def __exit__(self, *args): 

800 self.close() 

801 

802 def closelater(self, fd): 

803 return self._exitstack.enter_context(fd) 

804 

805 def close(self): 

806 self._exitstack.close() 

807 

808 def openfile(self, file, comm, mode='w'): 

809 if hasattr(file, 'close'): 

810 return file # File already opened, not for us to close. 

811 

812 encoding = None if mode.endswith('b') else 'utf-8' 

813 

814 if file is None or comm.rank != 0: 

815 return self.closelater( 

816 open(os.devnull, mode=mode, encoding=encoding) 

817 ) 

818 

819 if file == '-': 

820 return sys.stdout 

821 

822 return self.closelater(open(file, mode=mode, encoding=encoding)) 

823 

824 

825def get_python_package_path_description( 

826 package, default='module has no path' 

827) -> str: 

828 """Helper to get path description of a python package/module 

829 

830 If path has multiple elements, the first one is returned. 

831 If it is empty, the default is returned. 

832 Exceptions are returned as strings default+(exception). 

833 Always returns a string. 

834 """ 

835 try: 

836 p = list(package.__path__) 

837 if p: 

838 return str(p[0]) 

839 else: 

840 return default 

841 except Exception as ex: 

842 return f'{default} ({ex})' 

843 

844 

845class OldSpglibError(Exception): 

846 pass 

847 

848 

849def spglib_new_errorhandling(func): 

850 def spglib_wrapper(*args, **kwargs): 

851 # spglib<2.7.0 returns None when there is an error. 

852 # spglib 2.7.0 warns that this will become exceptions in the future. 

853 # We hack an environment setting to silence this warning and get the 

854 # behaviour we want. 

855 key = 'SPGLIB_OLD_ERROR_HANDLING' 

856 orig_value = os.environ.get(key) 

857 try: 

858 os.environ[key] = 'false' 

859 value = func(*args, **kwargs) 

860 if value is None: 

861 raise OldSpglibError() 

862 return value 

863 finally: 

864 if orig_value is not None: 

865 os.environ[key] = orig_value 

866 

867 return spglib_wrapper