From ffba5351ee8a7614023b632cc232c855de32da0d Mon Sep 17 00:00:00 2001 From: Shyue Ping Ong Date: Mon, 2 Oct 2023 08:55:02 -0700 Subject: [PATCH] Properly override __new__ for MPRester. --- pymatgen/ext/matproj.py | 18 ++++++++---------- tests/ext/test_matproj.py | 4 ++-- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/pymatgen/ext/matproj.py b/pymatgen/ext/matproj.py index ad6e1748e04..645f9e2c8de 100644 --- a/pymatgen/ext/matproj.py +++ b/pymatgen/ext/matproj.py @@ -376,19 +376,17 @@ def __new__(cls, *args, **kwargs): if not api_key: raise ValueError("Please supply an API key. See https://materialsproject.org/api for details.") - try: - from mp_api.client import MPRester as _MPResterNew - except Exception: - _MPResterNew = _MPResterBasic - - if len(api_key) == 32: - rester = _MPResterNew - else: + if len(api_key) != 32: from pymatgen.ext.matproj_legacy import _MPResterLegacy - rester = _MPResterLegacy + return _MPResterLegacy.__new__(cls) - return rester(*args, **kwargs) + try: + from mp_api.client import MPRester as _MPResterNew + + return _MPResterNew.__new__(cls) + except Exception: + return _MPResterBasic.__new__(cls) class MPRestError(Exception): diff --git a/tests/ext/test_matproj.py b/tests/ext/test_matproj.py index 4fdd85adc93..35582c76ac5 100644 --- a/tests/ext/test_matproj.py +++ b/tests/ext/test_matproj.py @@ -892,8 +892,8 @@ def test_get_structures(self): def test_parity_with_mp_api(self): try: from mp_api.client import MPRester as MPResterMPAPI - except ImportError: - pytest.importorskip("mp_api.client.MPRester") + except Exception: + pytest.skip("mp_api.client.MPRester cannot be imported for this test.") mpr_mpapi = MPResterMPAPI(PMG_MAPI_KEY) # Test summary mp_data = mpr_mpapi.summary.search(formula="Al2O3")