anthonypjshaw/SWE-bench_Complex huggingface dataset:
Repository: django/django

Issue:
# Fixed #36961 -- Fixed TypeError in deprecation warnings if Django is imported by namespace.

#### Trac ticket number
ticket-36961

#### Branch description
Found while testing #20300 -- I opened a shell, and tried to create a `Field.get_placeholder` method, but because my cwd was one level above my Django checkout, I had:
```py
>>> django.__file__ is None
True
```

Leading to a TypeError in this util.

#### AI Assistance Disclosure (REQUIRED)
- [x] **No AI tools were used** in preparing this PR.
- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.

#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [x] I have added or updated relevant docs, including release notes if applicable.
- [x] I have attached screenshots in both light and dark modes for any UI changes.


Implementation patch:
diff --git a/django/utils/deprecation.py b/django/utils/deprecation.py
index daa485eb35bf..4aa11832165e 100644
--- a/django/utils/deprecation.py
+++ b/django/utils/deprecation.py
@@ -13,9 +13,8 @@
 
 @functools.cache
 def django_file_prefixes():
-    try:
-        file = django.__file__
-    except AttributeError:
+    file = getattr(django, "__file__", None)
+    if file is None:
         return ()
     return (os.path.dirname(file),)
 


Test patch:
diff --git a/tests/deprecation/tests.py b/tests/deprecation/tests.py
index 2df9cc6fa219..ac610b492835 100644
--- a/tests/deprecation/tests.py
+++ b/tests/deprecation/tests.py
@@ -18,6 +18,10 @@ def setUp(self):
     def test_no_file(self):
         orig_file = django.__file__
         try:
+            # Depending on the cwd, Python might give a local checkout
+            # precedence over installed Django, producing None.
+            django.__file__ = None
+            self.assertEqual(django_file_prefixes(), ())
             del django.__file__
             self.assertEqual(django_file_prefixes(), ())
         finally:
Repository: django/django

Issue:
# Fixed #36812 -- Dropped support for MariaDB < 10.11.

#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number, or delete the line and write "N/A" if this is a trivial PR. -->

ticket-36812

#### Branch description
 Dropped the support for MariaDB 10.6-10.10.

#### Checklist
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [x] I have added or updated relevant docs, including release notes if applicable.
- [x] I have attached screenshots in both light and dark modes for any UI changes.


Implementation patch:
diff --git a/django/db/backends/mysql/features.py b/django/db/backends/mysql/features.py
index 4f61e2bdf9af..eb9601bcef44 100644
--- a/django/db/backends/mysql/features.py
+++ b/django/db/backends/mysql/features.py
@@ -64,7 +64,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):
     @cached_property
     def minimum_database_version(self):
         if self.connection.mysql_is_mariadb:
-            return (10, 6)
+            return (10, 11)
         else:
             return (8, 4)
 
@@ -207,8 +207,6 @@ def can_introspect_json_field(self):
     def supports_index_column_ordering(self):
         if self._mysql_storage_engine != "InnoDB":
             return False
-        if self.connection.mysql_is_mariadb:
-            return self.connection.mysql_version >= (10, 8)
         return True
 
     @cached_property
@@ -220,8 +218,7 @@ def supports_expression_indexes(self):
 
     @cached_property
     def has_native_uuid_field(self):
-        is_mariadb = self.connection.mysql_is_mariadb
-        return is_mariadb and self.connection.mysql_version >= (10, 7)
+        return self.connection.mysql_is_mariadb
 
     @cached_property
     def allows_group_by_selected_pks(self):


Test patch:
diff --git a/tests/backends/mysql/tests.py b/tests/backends/mysql/tests.py
index 15228d254fc1..237e7f94472b 100644
--- a/tests/backends/mysql/tests.py
+++ b/tests/backends/mysql/tests.py
@@ -106,8 +106,8 @@ class Tests(TestCase):
     @mock.patch.object(connection, "get_database_version")
     def test_check_database_version_supported(self, mocked_get_database_version):
         if connection.mysql_is_mariadb:
-            mocked_get_database_version.return_value = (10, 5)
-            msg = "MariaDB 10.6 or later is required (found 10.5)."
+            mocked_get_database_version.return_value = (10, 10)
+            msg = "MariaDB 10.11 or later is required (found 10.10)."
         else:
             mocked_get_database_version.return_value = (8, 0, 31)
             msg = "MySQL 8.4 or later is required (found 8.0.31)."
Repository: sympy/sympy

Issue:
# LaTeX printing of FreeGroupElements

Version: 1.15.0.dev (actually it has been a problem for quite a long time, not just 1.15)

Code: Consider calling `latex` on generators of a free group,
```
from sympy.combinatorics import free_group
from sympy.abc import a, b
from sympy import *
_, aa, bb = free_group((a,b))
print(latex(aa))
```

This will cause a RecursionError. As a side effect, displaying the generators of a free group in Jupyter notebooks will cause a RecursionError.

---

Apart from above, I tested calling `latex` over **words** instead of single generators, e.g.,
```
print(aa*bb**3*aa)
print(latex(aa*bb**3*aa))
```
This is the output:
```
a*b**3*a
\left( \left( a, \  1\right), \  \left( b, \  3\right), \  \left( a, \  1\right)\right)
```
Is it better to make `latex` print in a similar way as `str`?

Implementation patch:
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index 0a818615b0db..f87e8b9d2f80 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -2543,6 +2543,20 @@ def _print_OmegaPower(self, expr):
     def _print_Ordinal(self, expr):
         return " + ".join([self._print(arg) for arg in expr.args])
 
+    def _print_FreeGroupElement(self, elm):
+        if elm.is_identity:
+            return "1"
+
+        str_form = []
+        for g, power in elm.array_form:
+            s = str(g)
+            if power == 1:
+                str_form.append(s)
+            else:
+                str_form.append(s + "^{" + str(power) + "}")
+        mul_symbol = self._settings['mul_symbol_latex'] or ""
+        return mul_symbol.join(str_form)
+
     def _print_PolyElement(self, poly):
         mul_symbol = self._settings['mul_symbol_latex']
         return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol)


Test patch:
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index cacc8ab6ca53..74b614e2a402 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -1,6 +1,7 @@
 from sympy import MatAdd, MatMul, Array
 from sympy.algebras.quaternion import Quaternion
 from sympy.calculus.accumulationbounds import AccumBounds
+from sympy.combinatorics.free_groups import free_group
 from sympy.combinatorics.permutations import Cycle, Permutation, AppliedPermutation
 from sympy.concrete.products import Product
 from sympy.concrete.summations import Sum
@@ -1725,6 +1726,18 @@ def test_latex_Lambda():
     assert latex(Lambda((x, y), x + 1)) == r"\left( \left( x, \  y\right) \mapsto x + 1 \right)"
     assert latex(Lambda(x, x)) == r"\left( x \mapsto x \right)"
 
+
+def test_latex_FreeGroupElement():
+    F, a, b = free_group("a,b")
+
+    assert latex(a**0) == "1"
+    assert latex(a) == "a"
+    assert latex(a**-1) == "a^{-1}"
+    assert latex(a**3*b**2*a*b**(-1)) == "a^{3} b^{2} a b^{-1}"
+    assert latex(b**(-2)*a*b**3, mul_symbol='dot') == \
+        r"b^{-2} \cdot a \cdot b^{3}"
+
+
 def test_latex_PolyElement():
     Ruv, u, v = ring("u,v", ZZ)
     Rxyz, x, y, z = ring("x,y,z", Ruv)
Repository: sympy/sympy

Issue:
# nonlinsolve crashes with TypeError when using sign functions

```python
nonlinsolve([sign(x) - 1, x*y - 4], [x, y]) output:- TypeError

```

`Tested On:- sympy:- 1.14.0`

Implementation patch:
diff --git a/sympy/solvers/solveset.py b/sympy/solvers/solveset.py
index a16bc73062ab..a8db21d2a53e 100644
--- a/sympy/solvers/solveset.py
+++ b/sympy/solvers/solveset.py
@@ -3603,7 +3603,13 @@ def _solve_using_known_values(result, solver):
                             # corresponding complex soln.
                             if not isinstance(soln, (ImageSet, ConditionSet)):
                                 soln += solveset_complex(eq2, sym)  # might give ValueError with Abs
-                    except (NotImplementedError, ValueError):
+
+                        if not isinstance(soln, (FiniteSet, ImageSet, ConditionSet, Union)) and soln is not S.EmptySet:
+                            raise NotImplementedError(
+                                f"nonlinsolve cannot handle solution of type {type(soln).__name__} "
+                                f"for symbol {sym}. Got {soln} from equation {eq2}."
+                            )
+                    except ValueError:
                         # If solveset is not able to solve equation `eq2`. Next
                         # time we may get soln using next equation `eq2`
                         continue


Test patch:
diff --git a/sympy/solvers/tests/test_solveset.py b/sympy/solvers/tests/test_solveset.py
index 8547a5ddf3f1..87429fe70c49 100644
--- a/sympy/solvers/tests/test_solveset.py
+++ b/sympy/solvers/tests/test_solveset.py
@@ -1872,6 +1872,13 @@ def test_nonlinsolve_abs():
     raises(NotImplementedError, lambda: nonlinsolve([Abs(x) - 2, x + y], x, y))
 
 
+def test_nonlinsolve_sign():
+    raises(NotImplementedError, lambda: nonlinsolve([sign(x) - 1, x*y - 4], [x, y]))
+    raises(NotImplementedError, lambda: nonlinsolve([sign(x) - 1, x - y], [x, y]))
+    result = nonlinsolve([sign(x) - 1], [x])
+    assert isinstance(result, FiniteSet)
+
+
 def test_raise_exception_nonlinsolve():
     raises(IndexError, lambda: nonlinsolve([x**2 -1], []))
     raises(ValueError, lambda: nonlinsolve([x**2 -1]))
Repository: sympy/sympy

Issue:
# `Pow.as_real_imag` is inconsistent with evaluating `Pow(0, -1)` as ComplexInfinity

> Another example of something causing this issue: `1/Sum(1, (Symbol("p"), 8, 6))`
> 
> I think this boils down to the following inconsistency:
> - `Pow(0,-1).as_real_imag() == (nan, nan)`
> - `Sum(1, (Symbol("p"), 8, 6)).is_nonzero is None`
> - `Pow(Sum(1, (Symbol("p"), 8, 6)), -1).as_real_imag() == (Pow(Sum(1, (Symbol("p"), 8, 6)), -1), 0)`
> 
> I guess https://github.com/sympy/sympy/blob/c0adb406785d80e9b4bbe1f0c95e7357f371bb53/sympy/core/power.py#L1130-L1137 should have a case first about what to do if `not self.base.is_nonzero` when `not exp >= 0` 

 _Originally posted by @JasonGross in [#28218](https://github.com/sympy/sympy/issues/28218#issuecomment-3047313998)_

Implementation patch:
diff --git a/sympy/core/power.py b/sympy/core/power.py
index cc9e90066bc0..a29731d083a9 100644
--- a/sympy/core/power.py
+++ b/sympy/core/power.py
@@ -1132,9 +1132,14 @@ def as_real_imag(self, deep=True, **hints):
             from sympy.polys.polytools import poly
 
             exp = self.exp
+            if exp < 0 and self.base.is_zero:
+                return (S.NaN, S.NaN)
+
             re_e, im_e = self.base.as_real_imag(deep=deep)
+
             if not im_e:
                 return self, S.Zero
+
             a, b = symbols('a b', cls=Dummy)
             if exp >= 0:
                 if re_e.is_Number and im_e.is_Number:


Test patch:
diff --git a/sympy/core/tests/test_power.py b/sympy/core/tests/test_power.py
index 80ae48c525c2..d0405e33cba5 100644
--- a/sympy/core/tests/test_power.py
+++ b/sympy/core/tests/test_power.py
@@ -668,3 +668,9 @@ def test_issue_25165():
     e1 = (1/sqrt(( - x + 1)**2 + (x - 0.23)**4)).series(x, 0, 2)
     e2 = 0.998603724830355 + 1.02004923189934*x + O(x**2)
     assert all_close(e1, e2)
+
+
+def test_issue_28219():
+    assert Pow(S.Zero, -1, evaluate=False).as_real_imag() == (S.NaN, S.NaN)
+    x = Symbol('x', real=True)
+    assert Pow(x, -1, evaluate=False).as_real_imag() == (1/x, S.Zero)
Repository: astropy/astropy

Issue:
# BUG: avoid deprecated interface for mutating shape attibutes (io.fits)

### Description
ref #19126

<!-- Optional opt-out -->

- [ ] By checking this box, the PR author has requested that maintainers do **NOT** use the "Squash and Merge" button. Maintainers should respect this when possible; however, the final decision is at the discretion of the maintainer that merges the PR.


Implementation patch:
diff --git a/astropy/io/fits/util.py b/astropy/io/fits/util.py
index 14b353e78d72..ad74e20ab6bc 100644
--- a/astropy/io/fits/util.py
+++ b/astropy/io/fits/util.py
@@ -20,6 +20,7 @@
 from packaging.version import Version
 
 from astropy.utils import data
+from astropy.utils.compat import NUMPY_LT_2_5
 from astropy.utils.compat.optional_deps import HAS_DASK
 from astropy.utils.exceptions import AstropyUserWarning
 
@@ -870,7 +871,10 @@ def _rstrip_inplace(array):
     # Note: the code will work if this fails; the chunks will just be larger.
     if b.ndim > 2:
         try:
-            b.shape = -1, b.shape[-1]
+            if NUMPY_LT_2_5:
+                b.shape = -1, b.shape[-1]
+            else:
+                b._set_shape((-1, b.shape[-1]))
         except AttributeError:  # can occur for non-contiguous arrays
             pass
     for j in range(0, b.shape[0], bufsize):



Test patch:
diff --git a/astropy/io/fits/tests/test_image.py b/astropy/io/fits/tests/test_image.py
index 0d7b2d868035..2e6c1b31e310 100644
--- a/astropy/io/fits/tests/test_image.py
+++ b/astropy/io/fits/tests/test_image.py
@@ -9,6 +9,7 @@
 from numpy.testing import assert_equal
 
 from astropy.io import fits
+from astropy.utils.compat import NUMPY_LT_2_5
 from astropy.utils.data import get_pkg_data_filename
 from astropy.utils.exceptions import AstropyUserWarning
 
@@ -977,7 +978,12 @@ def test_open_scaled_in_update_mode(self):
 
         # Try reshaping the data, then closing and reopening the file; let's
         # see if all the changes are preserved properly
-        hdul[0].data.shape = (42, 10)
+        if NUMPY_LT_2_5:
+            hdul[0].data.shape = (42, 10)
+        else:
+            # ndarray._set_shape is semi-private, but the only
+            # non deprecated, strict semantic equivalent in Numpy 2.5+
+            hdul[0].data._set_shape((42, 10))
         hdul.close()
 
         hdul = fits.open(testfile)
@@ -988,6 +994,13 @@ def test_open_scaled_in_update_mode(self):
         assert "BSCALE" not in hdul[0].header
         hdul.close()
 
+        with fits.open(testfile, mode="update") as hdul:
+            # Try reshaping the data again, this time using np.reshape
+            hdul[0].data = np.reshape(hdul[0].data, (21, 20))
+
+        with fits.open(testfile) as hdul:
+            assert hdul[0].shape == (21, 20)
+
     def test_scale_back(self):
         """A simple test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/120
Repository: pydata/xarray

Issue:
# ⚠️ Nightly upstream-dev CI failed ⚠️

[Workflow Run URL](https://github.com/pydata/xarray/actions/runs/22881049985)
<details><summary>Python 3.12 Test Summary</summary>

```
xarray/tests/test_computation.py::test_fix: DeprecationWarning: numpy.fix is deprecated. Use numpy.trunc instead, which is faster and follows the Array API standard.
xarray/tests/test_dataarray.py::TestDataArray::test_curvefit_helpers: Failed: DID NOT RAISE <class 'ValueError'>
xarray/tests/test_variable.py::TestIndexVariable::test_concat_periods: ValueError: Could not convert <xarray.IndexVariable 't' (t: 5)> Size: 40B
<PeriodArray>
['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05']
Length: 5, dtype: period[D] to a NumPy dtype (via `.dtype` value period[D]).
```

</details>


Implementation patch:
diff --git a/xarray/core/utils.py b/xarray/core/utils.py
index c6828f0a363..100c256fa9d 100644
--- a/xarray/core/utils.py
+++ b/xarray/core/utils.py
@@ -205,7 +205,7 @@ def get_valid_numpy_dtype(array: np.ndarray | pd.Index) -> np.dtype:
 
 
 def maybe_coerce_to_str(index, original_coords):
-    """maybe coerce a pandas Index back to a nunpy array of type str
+    """maybe coerce a pandas Index back to a numpy array of type str
 
     pd.Index uses object-dtype to store str - try to avoid this for coords
     """
@@ -213,7 +213,7 @@ def maybe_coerce_to_str(index, original_coords):
 
     try:
         result_type = dtypes.result_type(*original_coords)
-    except TypeError:
+    except (TypeError, ValueError):
         pass
     else:
         if result_type.kind in "SU":


Test patch:
diff --git a/xarray/tests/test_computation.py b/xarray/tests/test_computation.py
index 84727cd210f..1cb8e6f4a3f 100644
--- a/xarray/tests/test_computation.py
+++ b/xarray/tests/test_computation.py
@@ -2646,6 +2646,7 @@ def test_complex_number_reduce(compute_backend):
     da.min()
 
 
+@pytest.mark.filterwarnings("ignore:numpy.fix is deprecated.")
 def test_fix() -> None:
     val = 3.0
     val_fixed = np.fix(val)
diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py
index dc4c29d1a68..5e514cc9767 100644
--- a/xarray/tests/test_dataarray.py
+++ b/xarray/tests/test_dataarray.py
@@ -4908,8 +4908,6 @@ def exp_decay(t, n0, tau=1):
         param_names = ["a"]
         params, func_args = _get_func_args(np.power, param_names)
         assert params == param_names
-        with pytest.raises(ValueError):
-            _get_func_args(np.power, [])
 
     @requires_scipy
     @pytest.mark.parametrize("use_dask", [True, False])
Repository: pydata/xarray

Issue:
# Slicing a MultiIndex level is broken

### What happened?

```python
import pandas as pd
import xarray as xr

midx = pd.MultiIndex.from_product([["a", "b"], [1, 2]], names=("foo", "bar"))
midx_coords = xr.Coordinates.from_pandas_multiindex(midx, dim="x")

ds = xr.Dataset(coords=midx_coords)
ds.sel(bar=slice(1, 2))
```
```
<xarray.Dataset> Size: 40B
Dimensions:  (foo: 4)
Coordinates:
  * foo      (foo) object 32B 'a' 'a' 'b' 'b'
    bar      object 8B slice(1, 2, None)
Data variables:
    *empty*
```

Possibly this cannot work, but we should raise an error in that case


Implementation patch:
diff --git a/xarray/core/indexes.py b/xarray/core/indexes.py
index 5c44a799229..664afc83590 100644
--- a/xarray/core/indexes.py
+++ b/xarray/core/indexes.py
@@ -1308,6 +1308,16 @@ def sel(self, labels, method=None, tolerance=None) -> IndexSelResult:
 
             has_slice = any(isinstance(v, slice) for v in label_values.values())
 
+            if has_slice:
+                slice_levels = [
+                    k for k, v in label_values.items() if isinstance(v, slice)
+                ]
+                raise ValueError(
+                    f"slice-based selection on multi-index level(s) {slice_levels} "
+                    f"is not supported. Use scalar values for multi-index level "
+                    f"selection instead, e.g., ``.sel({slice_levels[0]}=value)``."
+                )
+
             if len(label_values) == self.index.nlevels and not has_slice:
                 indexer = self.index.get_loc(
                     tuple(label_values[k] for k in self.index.names)


Test patch:
diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py
index 855f758e5fe..f00c5e4aed7 100644
--- a/xarray/tests/test_dataset.py
+++ b/xarray/tests/test_dataset.py
@@ -2246,6 +2246,12 @@ def test_sel(
 
         assert_identical(mdata.sel(x={"one": "a", "two": 1}), mdata.sel(one="a", two=1))
 
+        # GH10534: slicing on multi-index levels should raise
+        with pytest.raises(ValueError, match="slice-based selection on multi-index"):
+            mdata.sel(one=slice("a", "b"))
+        with pytest.raises(ValueError, match="slice-based selection on multi-index"):
+            mdata.sel(two=slice(1, 2))
+
     def test_broadcast_like(self) -> None:
         original1 = DataArray(
             np.random.randn(5), [("x", range(5))], name="a"
Repository: pydata/xarray

Issue:
# Nightly Hypothesis tests failed

[Workflow Run URL](https://github.com/pydata/xarray/actions/runs/21846931586)
<details><summary>Python 3.12 Test Summary</summary>

```
properties/test_index_manipulation.py::DatasetTest::runTest: ExceptionGroup: Hypothesis found 2 distinct failures. (2 sub-exceptions)
```

</details>


Implementation patch:
diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py
index a6de7e22771..054668a0317 100644
--- a/xarray/core/dataset.py
+++ b/xarray/core/dataset.py
@@ -5205,7 +5205,7 @@ def _stack_once(
                 vdims = list(var.dims) + add_dims
                 shape = [self.sizes[d] for d in vdims]
                 exp_var = var.set_dims(vdims, shape)
-                stacked_var = exp_var.stack(**{new_dim: dims})
+                stacked_var = exp_var.stack({new_dim: dims})
                 new_variables[name] = stacked_var
                 stacked_var_names.append(name)
             else:
diff --git a/xarray/core/indexes.py b/xarray/core/indexes.py
index f7eff589ca2..5c44a799229 100644
--- a/xarray/core/indexes.py
+++ b/xarray/core/indexes.py
@@ -536,7 +536,13 @@ def safe_cast_to_index(array: Any) -> pd.Index:
                 )
                 kwargs["dtype"] = "float64"
 
-        index = pd.Index(to_numpy(array), **kwargs)
+        values = to_numpy(array)
+        try:
+            index = pd.Index(values, **kwargs)
+        except UnicodeEncodeError:
+            # coerce to object if pandas fails to coerce to string
+            kwargs["dtype"] = "object"
+            index = pd.Index(values, **kwargs)
 
     return _maybe_cast_to_cftimeindex(index)
 



Test patch:
diff --git a/properties/test_index_manipulation.py b/properties/test_index_manipulation.py
index 6df5b1370e3..c7e1a1bbd7b 100644
--- a/properties/test_index_manipulation.py
+++ b/properties/test_index_manipulation.py
@@ -269,6 +269,13 @@ def assert_invariants(self):
 DatasetTest = DatasetStateMachine.TestCase
 
 
+@pytest.mark.skip(reason="failure detected by hypothesis")
+def test_unstack_string():
+    ds = xr.Dataset()
+    ds["0"] = np.array(["", "0", "\x000"], dtype="<U2")
+    ds.stack({"1": ["0"]}).unstack()
+
+
 @pytest.mark.skip(reason="failure detected by hypothesis")
 def test_unstack_object():
     ds = xr.Dataset()
Repository: pylint-dev/pylint

Issue:
# Fix setting options for import order checker

## Type of Changes

|     | Type                   |
| --- | ---------------------- |
| ✓   | :bug: Bug fix          |

## Description

Fix regression in 6ce60320a:
In `__init__` the options are not parsed yet and hence will always be the defaults.


Closes #10801


I was looking for a way to avoid this in general. However that requires a bit more refactoring to either:
- Don't set `PyLinter.options` on `__init__.py` to detect access to it before being set (from config)
- (Preferred): Don't init plugins until options are parsed. Registering would register the classes instead of the instances

Implementation patch:
diff --git a/pylint/checkers/imports.py b/pylint/checkers/imports.py
index b045f74c21..039fd7cc9f 100644
--- a/pylint/checkers/imports.py
+++ b/pylint/checkers/imports.py
@@ -318,6 +318,7 @@ def _make_graph(
 
 
 DEFAULT_STANDARD_LIBRARY = ()
+DEFAULT_KNOWN_FIRST_PARTY = ()
 DEFAULT_KNOWN_THIRD_PARTY = ("enchant",)
 DEFAULT_PREFERRED_MODULES = ()
 
@@ -401,6 +402,16 @@ class ImportsChecker(DeprecatedMixin, BaseChecker):
                 "the standard compatibility libraries.",
             },
         ),
+        (
+            "known-first-party",
+            {
+                "default": DEFAULT_KNOWN_FIRST_PARTY,
+                "type": "csv",
+                "metavar": "<modules>",
+                "help": "Force import order to recognize a module as part of "
+                "a first party library.",
+            },
+        ),
         (
             "known-third-party",
             {
@@ -758,6 +769,7 @@ def _isort_config(self) -> isort.Config:
             # KNOWN_standard_library for ages in pylint, and we
             # don't want to break compatibility.
             extra_standard_library=self.linter.config.known_standard_library,
+            known_first_party=self.linter.config.known_first_party,
             known_third_party=self.linter.config.known_third_party,
         )
 


Test patch:
diff --git a/tests/functional/w/wrong_import_order2.py b/tests/functional/w/wrong_import_order2.py
index 6f68906738..be24704a49 100644
--- a/tests/functional/w/wrong_import_order2.py
+++ b/tests/functional/w/wrong_import_order2.py
@@ -6,12 +6,16 @@
 import os
 from sys import argv
 
-# external imports
+# external/third-party imports
 import isort
 import datetime  # std import that should be treated as third-party
 
+# First-party imports
 from six import moves
 
+import pylint
+import re  # std import that should be treated as first-party
+
 # local_imports
 from . import my_package
 from .my_package import myClass