repo
string
instance_id
string
base_commit
string
patch
string
test_patch
string
problem_statement
string
hints_text
string
created_at
string
version
string
FAIL_TO_PASS
string
PASS_TO_PASS
string
environment_setup_commit
string
django/django
django__django-11001
ef082ebb84f00e38af4e8880d04e8365c2766d34
diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -32,7 +32,8 @@ def __init__(self, query, connection, using): self.select = None self.annotation_col_map = None self.klass_info = None - self.ordering_parts = re.compile(r'(.*)\s(ASC|DESC)(.*)') + # Multiline ordering SQL clause may appear from RawSQL. + self.ordering_parts = re.compile(r'^(.*)\s(ASC|DESC)(.*)', re.MULTILINE | re.DOTALL) self._meta_ordering = None def setup_query(self):
diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -384,6 +384,29 @@ def test_order_by_exists(self): ) self.assertSequenceEqual(mustermanns_by_seniority, [self.max, mary]) + def test_order_by_multiline_sql(self): + raw_order_by = ( + RawSQL(''' + CASE WHEN num_employees > 1000 + THEN num_chairs + ELSE 0 END + ''', []).desc(), + RawSQL(''' + CASE WHEN num_chairs > 1 + THEN 1 + ELSE 0 END + ''', []).asc() + ) + for qs in ( + Company.objects.all(), + Company.objects.distinct(), + ): + with self.subTest(qs=qs): + self.assertSequenceEqual( + qs.order_by(*raw_order_by), + [self.example_inc, self.gmbh, self.foobar_ltd], + ) + def test_outerref(self): inner = Company.objects.filter(point_of_contact=OuterRef('pk')) msg = (
Incorrect removal of order_by clause created as multiline RawSQL Description Hi. The SQLCompiler is ripping off one of my "order by" clause, because he "thinks" the clause was already "seen" (in SQLCompiler.get_order_by()). I'm using expressions written as multiline RawSQLs, which are similar but not the same. The bug is located in SQLCompiler.get_order_by(), somewhere around line computing part of SQL query without ordering: without_ordering = self.ordering_parts.search(sql).group(1) The sql variable contains multiline sql. As a result, the self.ordering_parts regular expression is returning just a line containing ASC or DESC words. This line is added to seen set, and because my raw queries have identical last lines, only the first clasue is returing from SQLCompiler.get_order_by(). As a quick/temporal fix I can suggest making sql variable clean of newline characters, like this: sql_oneline = ' '.join(sql.split('\n')) without_ordering = self.ordering_parts.search(sql_oneline).group(1) Note: beware of unicode (Py2.x u'') and EOL dragons (\r). Example of my query: return MyModel.objects.all().order_by( RawSQL(''' case when status in ('accepted', 'verification') then 2 else 1 end''', []).desc(), RawSQL(''' case when status in ('accepted', 'verification') then (accepted_datetime, preferred_datetime) else null end''', []).asc(), RawSQL(''' case when status not in ('accepted', 'verification') then (accepted_datetime, preferred_datetime, created_at) else null end''', []).desc()) The ordering_parts.search is returing accordingly: ' then 2 else 1 end)' ' else null end' ' else null end' Second RawSQL with a else null end part is removed from query. The fun thing is that the issue can be solved by workaround by adding a space or any other char to the last line. So in case of RawSQL I can just say, that current implementation of avoiding duplicates in order by clause works only for special/rare cases (or does not work in all cases). The bug filed here is about wrong identification of duplicates (because it compares only last line of SQL passed to order by clause). Hope my notes will help you fixing the issue. Sorry for my english.
Is there a reason you can't use ​conditional expressions, e.g. something like: MyModel.objects.annotate( custom_order=Case( When(...), ) ).order_by('custom_order') I'm thinking that would avoid fiddly ordering_parts regular expression. If there's some shortcoming to that approach, it might be easier to address that. Allowing the ordering optimization stuff to handle arbitrary RawSQL may be difficult. Is there a reason you can't use ​conditional expressions No, but I didn't knew about the issue, and writing raw sqls is sometimes faster (not in this case ;) I'm really happy having possibility to mix raw sqls with object queries. Next time I'll use expressions, for sure. Allowing the ordering optimization stuff to handle arbitrary RawSQL may be difficult. Personally I'd like to skip RawSQL clauses in the block which is responsible for finding duplicates. If someone is using raw sqls, he knows the best what he is doing, IMO. And it is quite strange if Django removes silently part of your SQL. This is very confusing. And please note that printing a Query instance was generating incomplete sql, but while checking Query.order_by manually, the return value was containing all clauses. I thought that just printing was affected, but our QA dept told me the truth ;) I know there is no effective way to compare similarity of two raw clauses. This may be hard for expression objects, too, but you have a possibility to implement some __eq__ magic (instead of comparation of generated sqls). Unfortunately I don't know why duplicates detection was implemented, so it's hard to tell how to improve this part. Patches welcome, I suppose. ​PR Is there a reason why you didn't add tests? I was waiting for confirmation, I've added a test. Is it enough? Some additional test coverage needed.
2019-02-17T13:02:09Z
3.0
["test_order_by_multiline_sql (expressions.tests.BasicExpressionsTests)", "test_order_of_operations (expressions.tests.BasicExpressionsTests)"]
["test_deconstruct (expressions.tests.FTests)", "test_deepcopy (expressions.tests.FTests)", "test_equal (expressions.tests.FTests)", "test_hash (expressions.tests.FTests)", "test_not_equal_Value (expressions.tests.FTests)", "test_and (expressions.tests.CombinableTests)", "test_negation (expressions.tests.CombinableTests)", "test_or (expressions.tests.CombinableTests)", "test_reversed_and (expressions.tests.CombinableTests)", "test_reversed_or (expressions.tests.CombinableTests)", "test_aggregates (expressions.tests.ReprTests)", "test_distinct_aggregates (expressions.tests.ReprTests)", "test_expressions (expressions.tests.ReprTests)", "test_filtered_aggregates (expressions.tests.ReprTests)", "test_functions (expressions.tests.ReprTests)", "test_equal (expressions.tests.SimpleExpressionTests)", "test_hash (expressions.tests.SimpleExpressionTests)", "test_month_aggregation (expressions.tests.FieldTransformTests)", "test_multiple_transforms_in_values (expressions.tests.FieldTransformTests)", "test_transform_in_values (expressions.tests.FieldTransformTests)", "test_deconstruct (expressions.tests.ValueTests)", "test_deconstruct_output_field (expressions.tests.ValueTests)", "test_equal (expressions.tests.ValueTests)", "test_equal_output_field (expressions.tests.ValueTests)", "test_hash (expressions.tests.ValueTests)", "test_raise_empty_expressionlist (expressions.tests.ValueTests)", "test_update_TimeField_using_Value (expressions.tests.ValueTests)", "test_update_UUIDField_using_Value (expressions.tests.ValueTests)", "test_complex_expressions (expressions.tests.ExpressionsNumericTests)", "test_fill_with_value_from_same_object (expressions.tests.ExpressionsNumericTests)", "test_filter_not_equals_other_field (expressions.tests.ExpressionsNumericTests)", "test_increment_value (expressions.tests.ExpressionsNumericTests)", "test_F_reuse (expressions.tests.ExpressionsTests)", "test_insensitive_patterns_escape (expressions.tests.ExpressionsTests)", "test_patterns_escape (expressions.tests.ExpressionsTests)", "test_complex_expressions_do_not_introduce_sql_injection_via_untrusted_string_inclusion (expressions.tests.IterableLookupInnerExpressionsTests)", "test_expressions_in_lookups_join_choice (expressions.tests.IterableLookupInnerExpressionsTests)", "test_in_lookup_allows_F_expressions_and_expressions_for_datetimes (expressions.tests.IterableLookupInnerExpressionsTests)", "test_in_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)", "test_range_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)", "test_lefthand_addition (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_and (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_left_shift_operator (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_or (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_right_shift_operator (expressions.tests.ExpressionOperatorTests)", "test_lefthand_division (expressions.tests.ExpressionOperatorTests)", "test_lefthand_modulo (expressions.tests.ExpressionOperatorTests)", "test_lefthand_multiplication (expressions.tests.ExpressionOperatorTests)", "test_lefthand_power (expressions.tests.ExpressionOperatorTests)", "test_lefthand_subtraction (expressions.tests.ExpressionOperatorTests)", "test_right_hand_addition (expressions.tests.ExpressionOperatorTests)", "test_right_hand_division (expressions.tests.ExpressionOperatorTests)", "test_right_hand_modulo (expressions.tests.ExpressionOperatorTests)", "test_right_hand_multiplication (expressions.tests.ExpressionOperatorTests)", "test_right_hand_subtraction (expressions.tests.ExpressionOperatorTests)", "test_righthand_power (expressions.tests.ExpressionOperatorTests)", "test_aggregate_subquery_annotation (expressions.tests.BasicExpressionsTests)", "test_annotate_values_aggregate (expressions.tests.BasicExpressionsTests)", "test_annotate_values_count (expressions.tests.BasicExpressionsTests)", "test_annotate_values_filter (expressions.tests.BasicExpressionsTests)", "test_annotation_with_outerref (expressions.tests.BasicExpressionsTests)", "test_annotations_within_subquery (expressions.tests.BasicExpressionsTests)", "test_arithmetic (expressions.tests.BasicExpressionsTests)", "test_exist_single_field_output_field (expressions.tests.BasicExpressionsTests)", "test_explicit_output_field (expressions.tests.BasicExpressionsTests)", "test_filter_inter_attribute (expressions.tests.BasicExpressionsTests)", "test_filter_with_join (expressions.tests.BasicExpressionsTests)", "test_filtering_on_annotate_that_uses_q (expressions.tests.BasicExpressionsTests)", "test_in_subquery (expressions.tests.BasicExpressionsTests)", "test_incorrect_field_in_F_expression (expressions.tests.BasicExpressionsTests)", "test_incorrect_joined_field_in_F_expression (expressions.tests.BasicExpressionsTests)", "test_nested_subquery (expressions.tests.BasicExpressionsTests)", "test_nested_subquery_outer_ref_2 (expressions.tests.BasicExpressionsTests)", "test_nested_subquery_outer_ref_with_autofield (expressions.tests.BasicExpressionsTests)", "test_new_object_create (expressions.tests.BasicExpressionsTests)", "test_new_object_save (expressions.tests.BasicExpressionsTests)", "test_object_create_with_aggregate (expressions.tests.BasicExpressionsTests)", "test_object_update (expressions.tests.BasicExpressionsTests)", "test_object_update_fk (expressions.tests.BasicExpressionsTests)", "test_object_update_unsaved_objects (expressions.tests.BasicExpressionsTests)", "test_order_by_exists (expressions.tests.BasicExpressionsTests)", "test_outerref (expressions.tests.BasicExpressionsTests)", "test_outerref_mixed_case_table_name (expressions.tests.BasicExpressionsTests)", "test_outerref_with_operator (expressions.tests.BasicExpressionsTests)", "test_parenthesis_priority (expressions.tests.BasicExpressionsTests)", "test_pickle_expression (expressions.tests.BasicExpressionsTests)", "test_subquery (expressions.tests.BasicExpressionsTests)", "test_subquery_filter_by_aggregate (expressions.tests.BasicExpressionsTests)", "test_subquery_references_joined_table_twice (expressions.tests.BasicExpressionsTests)", "test_ticket_11722_iexact_lookup (expressions.tests.BasicExpressionsTests)", "test_ticket_16731_startswith_lookup (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_chained_filters (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_join_reuse (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_kwarg_ordering (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_kwarg_ordering_2 (expressions.tests.BasicExpressionsTests)", "test_update (expressions.tests.BasicExpressionsTests)", "test_update_inherited_field_value (expressions.tests.BasicExpressionsTests)", "test_update_with_fk (expressions.tests.BasicExpressionsTests)", "test_update_with_none (expressions.tests.BasicExpressionsTests)", "test_uuid_pk_subquery (expressions.tests.BasicExpressionsTests)", "test_date_comparison (expressions.tests.FTimeDeltaTests)", "test_date_minus_duration (expressions.tests.FTimeDeltaTests)", "test_date_subtraction (expressions.tests.FTimeDeltaTests)", "test_datetime_subtraction (expressions.tests.FTimeDeltaTests)", "test_datetime_subtraction_microseconds (expressions.tests.FTimeDeltaTests)", "test_delta_add (expressions.tests.FTimeDeltaTests)", "test_delta_subtract (expressions.tests.FTimeDeltaTests)", "test_delta_update (expressions.tests.FTimeDeltaTests)", "test_duration_with_datetime (expressions.tests.FTimeDeltaTests)", "test_duration_with_datetime_microseconds (expressions.tests.FTimeDeltaTests)", "test_durationfield_add (expressions.tests.FTimeDeltaTests)", "test_exclude (expressions.tests.FTimeDeltaTests)", "test_invalid_operator (expressions.tests.FTimeDeltaTests)", "test_mixed_comparisons2 (expressions.tests.FTimeDeltaTests)", "test_multiple_query_compilation (expressions.tests.FTimeDeltaTests)", "test_negative_timedelta_update (expressions.tests.FTimeDeltaTests)", "test_query_clone (expressions.tests.FTimeDeltaTests)", "test_time_subtraction (expressions.tests.FTimeDeltaTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11999
84633905273fc916e3d17883810d9969c03f73c2
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -763,8 +763,12 @@ def contribute_to_class(self, cls, name, private_only=False): if not getattr(cls, self.attname, None): setattr(cls, self.attname, self.descriptor_class(self)) if self.choices is not None: - setattr(cls, 'get_%s_display' % self.name, - partialmethod(cls._get_FIELD_display, field=self)) + if not hasattr(cls, 'get_%s_display' % self.name): + setattr( + cls, + 'get_%s_display' % self.name, + partialmethod(cls._get_FIELD_display, field=self), + ) def get_filter_kwargs_for_object(self, obj): """
diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py --- a/tests/model_fields/tests.py +++ b/tests/model_fields/tests.py @@ -168,6 +168,16 @@ def test_get_FIELD_display_translated(self): self.assertIsInstance(val, str) self.assertEqual(val, 'translated') + def test_overriding_FIELD_display(self): + class FooBar(models.Model): + foo_bar = models.IntegerField(choices=[(1, 'foo'), (2, 'bar')]) + + def get_foo_bar_display(self): + return 'something' + + f = FooBar(foo_bar=1) + self.assertEqual(f.get_foo_bar_display(), 'something') + def test_iterator_choices(self): """ get_choices() works with Iterators.
Cannot override get_FOO_display() in Django 2.2+. Description I cannot override the get_FIELD_display function on models since version 2.2. It works in version 2.1. Example: class FooBar(models.Model): foo_bar = models.CharField(_("foo"), choices=[(1, 'foo'), (2, 'bar')]) def __str__(self): return self.get_foo_bar_display() # This returns 'foo' or 'bar' in 2.2, but 'something' in 2.1 def get_foo_bar_display(self): return "something" What I expect is that I should be able to override this function.
Thanks for this report. Regression in a68ea231012434b522ce45c513d84add516afa60. Reproduced at 54a7b021125d23a248e70ba17bf8b10bc8619234. OK, I have a lead on this. Not at all happy about how it looks at first pass, but I'll a proof of concept PR together for it tomorrow AM. I don't think it should be marked as blocker since it looks like it was never supported, because it depends on the order of attrs passed in ModelBase.__new__(). So on Django 2.1 and Python 3.7: In [1]: import django ...: django.VERSION In [2]: from django.db import models ...: ...: class FooBar(models.Model): ...: def get_foo_bar_display(self): ...: return "something" ...: ...: foo_bar = models.CharField("foo", choices=[(1, 'foo'), (2, 'bar')]) ...: ...: def __str__(self): ...: return self.get_foo_bar_display() # This returns 'foo' or 'bar' in 2.2, but 'something' in 2.1 ...: ...: class Meta: ...: app_label = 'test' ...: ...: FooBar(foo_bar=1) Out[2]: <FooBar: foo> Before ​Python 3.6 the order of attrs wasn't defined at all. Sergey, an example from the ticket description works for me with Django 2.1 and Python 3.6, 3.7 and 3.8. In [2]: import django ...: django.VERSION Out[2]: (2, 1, 13, 'final', 0) In [3]: import sys ...: sys.version Out[3]: '3.5.7 (default, Oct 17 2019, 07:04:41) \n[GCC 8.3.0]' In [4]: from django.db import models ...: ...: class FooBar(models.Model): ...: foo_bar = models.CharField("foo", choices=[(1, 'foo'), (2, 'bar')]) ...: ...: def __str__(self): ...: return self.get_foo_bar_display() # This returns 'foo' or 'bar' in 2.2, but 'something' in 2.1 ...: ...: def get_foo_bar_display(self): ...: return "something" ...: ...: class Meta: ...: app_label = 'test' ...: ...: FooBar(foo_bar=1) Out[4]: <FooBar: foo> OK, so there is a behaviour change here, but Sergey is correct that it does depend on attr order, so it's hard to say that this can be said to ever have been thought of as supported, with the exact example provided. This example produces the opposite result on 2.1 (even on >=PY36): def test_overriding_display_backwards(self): class FooBar2(models.Model): def get_foo_bar_display(self): return "something" foo_bar = models.CharField("foo", choices=[(1, 'foo'), (2, 'bar')]) f = FooBar2(foo_bar=1) # This returns 'foo' or 'bar' in both 2.2 and 2.1 self.assertEqual(f.get_foo_bar_display(), "foo") Because get_foo_bar_display() is defined before foo_bar is gets replaced in the the add_to_class() step. Semantically order shouldn't make a difference. Given that it does, I can't see that we're bound to maintain that behaviour. (There's a possible fix in Field.contribute_to_class() but implementing that just reverses the pass/fail behaviour depending on order...) Rather, the correct way to implement this on 2.2+ is: def test_overriding_display(self): class FooBar(models.Model): foo_bar = models.CharField("foo", choices=[(1, 'foo'), (2, 'bar')]) def _get_FIELD_display(self, field): if field.attname == 'foo_bar': return "something" return super()._get_FIELD_display(field) f = FooBar(foo_bar=1) self.assertEqual(f.get_foo_bar_display(), "something") This is stable for declaration order on version 2.2+. This approach requires overriding _get_FIELD_display() before declaring fields on 2.1, because otherwise Model._get_FIELD_display() is picked up during Field.contribute_to_class(). This ordering dependency is, ultimately, the same issue that was addressed in a68ea231012434b522ce45c513d84add516afa60, and the follow-up in #30254. The behaviour in 2.1 (and before) was incorrect. Yes, there's a behaviour change here but it's a bugfix, and all bugfixes are breaking changes if you're depending on the broken behaviour. I'm going to downgrade this from Release Blocker accordingly. I'll reclassify this as a Documentation issue and provide the working example, as overriding _get_FIELD_display() is a legitimate use-case I'd guess. Replying to Carlton Gibson: (There's a possible fix in Field.contribute_to_class() but implementing that just reverses the pass/fail behaviour depending on order...) Doesn't this fix it? if not hasattr(cls, 'get_%s_display' % self.name): setattr(cls, 'get_%s_display' % self.name, partialmethod(cls._get_FIELD_display, field=self))
2019-10-31T10:39:18Z
3.1
["test_overriding_FIELD_display (model_fields.tests.GetFieldDisplayTests)"]
["test_blank_in_choices (model_fields.tests.GetChoicesTests)", "test_blank_in_grouped_choices (model_fields.tests.GetChoicesTests)", "test_empty_choices (model_fields.tests.GetChoicesTests)", "test_lazy_strings_not_evaluated (model_fields.tests.GetChoicesTests)", "test_check (model_fields.tests.ChoicesTests)", "test_choices (model_fields.tests.ChoicesTests)", "test_flatchoices (model_fields.tests.ChoicesTests)", "test_formfield (model_fields.tests.ChoicesTests)", "test_invalid_choice (model_fields.tests.ChoicesTests)", "Can supply a custom choices form class to Field.formfield()", "deconstruct() uses __qualname__ for nested class support.", "Field instances can be pickled.", "test_field_name (model_fields.tests.BasicFieldTests)", "Fields are ordered based on their creation.", "test_field_repr (model_fields.tests.BasicFieldTests)", "__repr__() uses __qualname__ for nested class support.", "test_field_str (model_fields.tests.BasicFieldTests)", "test_field_verbose_name (model_fields.tests.BasicFieldTests)", "Field.formfield() sets disabled for fields with choices.", "test_show_hidden_initial (model_fields.tests.BasicFieldTests)", "test_choices_and_field_display (model_fields.tests.GetFieldDisplayTests)", "test_empty_iterator_choices (model_fields.tests.GetFieldDisplayTests)", "A translated display value is coerced to str.", "test_iterator_choices (model_fields.tests.GetFieldDisplayTests)", "test_get_choices (model_fields.tests.GetChoicesLimitChoicesToTests)", "test_get_choices_reverse_related_field (model_fields.tests.GetChoicesLimitChoicesToTests)", "test_get_choices (model_fields.tests.GetChoicesOrderingTests)", "test_get_choices_default_ordering (model_fields.tests.GetChoicesOrderingTests)", "test_get_choices_reverse_related_field (model_fields.tests.GetChoicesOrderingTests)", "test_get_choices_reverse_related_field_default_ordering (model_fields.tests.GetChoicesOrderingTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12184
5d674eac871a306405b0fbbaeb17bbeba9c68bf3
diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py --- a/django/urls/resolvers.py +++ b/django/urls/resolvers.py @@ -158,8 +158,9 @@ def match(self, path): # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as # positional arguments. - kwargs = {k: v for k, v in match.groupdict().items() if v is not None} + kwargs = match.groupdict() args = () if kwargs else match.groups() + kwargs = {k: v for k, v in kwargs.items() if v is not None} return path[match.end():], args, kwargs return None
diff --git a/tests/urlpatterns/path_urls.py b/tests/urlpatterns/path_urls.py --- a/tests/urlpatterns/path_urls.py +++ b/tests/urlpatterns/path_urls.py @@ -12,6 +12,11 @@ path('included_urls/', include('urlpatterns.included_urls')), re_path(r'^regex/(?P<pk>[0-9]+)/$', views.empty_view, name='regex'), re_path(r'^regex_optional/(?P<arg1>\d+)/(?:(?P<arg2>\d+)/)?', views.empty_view, name='regex_optional'), + re_path( + r'^regex_only_optional/(?:(?P<arg1>\d+)/)?', + views.empty_view, + name='regex_only_optional', + ), path('', include('urlpatterns.more_urls')), path('<lang>/<path:url>/', views.empty_view, name='lang-and-path'), ] diff --git a/tests/urlpatterns/tests.py b/tests/urlpatterns/tests.py --- a/tests/urlpatterns/tests.py +++ b/tests/urlpatterns/tests.py @@ -68,6 +68,16 @@ def test_re_path_with_optional_parameter(self): r'^regex_optional/(?P<arg1>\d+)/(?:(?P<arg2>\d+)/)?', ) + def test_re_path_with_missing_optional_parameter(self): + match = resolve('/regex_only_optional/') + self.assertEqual(match.url_name, 'regex_only_optional') + self.assertEqual(match.kwargs, {}) + self.assertEqual(match.args, ()) + self.assertEqual( + match.route, + r'^regex_only_optional/(?:(?P<arg1>\d+)/)?', + ) + def test_path_lookup_with_inclusion(self): match = resolve('/included_urls/extra/something/') self.assertEqual(match.url_name, 'inner-extra')
Optional URL params crash some view functions. Description My use case, running fine with Django until 2.2: URLConf: urlpatterns += [ ... re_path(r'^module/(?P<format>(html|json|xml))?/?$', views.modules, name='modules'), ] View: def modules(request, format='html'): ... return render(...) With Django 3.0, this is now producing an error: Traceback (most recent call last): File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /module/ Exception Value: modules() takes from 1 to 2 positional arguments but 3 were given
Tracked regression in 76b993a117b61c41584e95149a67d8a1e9f49dd1. It seems to work if you remove the extra parentheses: re_path(r'^module/(?P<format>html|json|xml)?/?$', views.modules, name='modules'), It seems Django is getting confused by the nested groups.
2019-12-05T13:09:48Z
3.1
["test_re_path_with_missing_optional_parameter (urlpatterns.tests.SimplifiedURLTests)"]
["test_allows_non_ascii_but_valid_identifiers (urlpatterns.tests.ParameterRestrictionTests)", "test_non_identifier_parameter_name_causes_exception (urlpatterns.tests.ParameterRestrictionTests)", "test_matching_urls (urlpatterns.tests.ConverterTests)", "test_nonmatching_urls (urlpatterns.tests.ConverterTests)", "test_resolve_type_error_propagates (urlpatterns.tests.ConversionExceptionTests)", "test_resolve_value_error_means_no_match (urlpatterns.tests.ConversionExceptionTests)", "test_reverse_value_error_propagates (urlpatterns.tests.ConversionExceptionTests)", "test_converter_resolve (urlpatterns.tests.SimplifiedURLTests)", "test_converter_reverse (urlpatterns.tests.SimplifiedURLTests)", "test_converter_reverse_with_second_layer_instance_namespace (urlpatterns.tests.SimplifiedURLTests)", "test_invalid_converter (urlpatterns.tests.SimplifiedURLTests)", "test_path_inclusion_is_matchable (urlpatterns.tests.SimplifiedURLTests)", "test_path_inclusion_is_reversible (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_double_inclusion (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_empty_string_inclusion (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_inclusion (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_multiple_parameters (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_typed_parameters (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_without_parameters (urlpatterns.tests.SimplifiedURLTests)", "test_path_reverse_with_parameter (urlpatterns.tests.SimplifiedURLTests)", "test_path_reverse_without_parameter (urlpatterns.tests.SimplifiedURLTests)", "test_re_path (urlpatterns.tests.SimplifiedURLTests)", "test_re_path_with_optional_parameter (urlpatterns.tests.SimplifiedURLTests)", "test_space_in_route (urlpatterns.tests.SimplifiedURLTests)", "test_two_variable_at_start_of_path_pattern (urlpatterns.tests.SimplifiedURLTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12113
62254c5202e80a68f4fe6572a2be46a3d953de1a
diff --git a/django/db/backends/sqlite3/creation.py b/django/db/backends/sqlite3/creation.py --- a/django/db/backends/sqlite3/creation.py +++ b/django/db/backends/sqlite3/creation.py @@ -98,4 +98,6 @@ def test_db_signature(self): sig = [self.connection.settings_dict['NAME']] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) + else: + sig.append(test_database_name) return tuple(sig)
diff --git a/tests/backends/sqlite/test_creation.py b/tests/backends/sqlite/test_creation.py new file mode 100644 --- /dev/null +++ b/tests/backends/sqlite/test_creation.py @@ -0,0 +1,18 @@ +import copy +import unittest + +from django.db import connection +from django.test import SimpleTestCase + + +@unittest.skipUnless(connection.vendor == 'sqlite', 'SQLite tests') +class TestDbSignatureTests(SimpleTestCase): + def test_custom_test_name(self): + saved_settings = copy.deepcopy(connection.settings_dict) + try: + connection.settings_dict['NAME'] = None + connection.settings_dict['TEST']['NAME'] = 'custom.sqlite.db' + signature = connection.creation.test_db_signature() + self.assertEqual(signature, (None, 'custom.sqlite.db')) + finally: + connection.settings_dict = saved_settings
admin_views.test_multidb fails with persistent test SQLite database. Description (last modified by Mariusz Felisiak) I've tried using persistent SQLite databases for the tests (to make use of --keepdb), but at least some test fails with: sqlite3.OperationalError: database is locked This is not an issue when only using TEST["NAME"] with "default" (which is good enough in terms of performance). diff --git i/tests/test_sqlite.py w/tests/test_sqlite.py index f1b65f7d01..9ce4e32e14 100644 --- i/tests/test_sqlite.py +++ w/tests/test_sqlite.py @@ -15,9 +15,15 @@ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', + 'TEST': { + 'NAME': 'test_default.sqlite3' + }, }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', + 'TEST': { + 'NAME': 'test_other.sqlite3' + }, } } % tests/runtests.py admin_views.test_multidb -v 3 --keepdb --parallel 1 … Operations to perform: Synchronize unmigrated apps: admin_views, auth, contenttypes, messages, sessions, staticfiles Apply all migrations: admin, sites Running pre-migrate handlers for application contenttypes Running pre-migrate handlers for application auth Running pre-migrate handlers for application sites Running pre-migrate handlers for application sessions Running pre-migrate handlers for application admin Running pre-migrate handlers for application admin_views Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No migrations to apply. Running post-migrate handlers for application contenttypes Running post-migrate handlers for application auth Running post-migrate handlers for application sites Running post-migrate handlers for application sessions Running post-migrate handlers for application admin Running post-migrate handlers for application admin_views System check identified no issues (0 silenced). ERROR ====================================================================== ERROR: setUpClass (admin_views.test_multidb.MultiDatabaseTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/sqlite3/base.py", line 391, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: database is locked The above exception was the direct cause of the following exception: Traceback (most recent call last): File "…/Vcs/django/django/test/testcases.py", line 1137, in setUpClass cls.setUpTestData() File "…/Vcs/django/tests/admin_views/test_multidb.py", line 40, in setUpTestData username='admin', password='something', email='test@test.org', File "…/Vcs/django/django/contrib/auth/models.py", line 158, in create_superuser return self._create_user(username, email, password, **extra_fields) File "…/Vcs/django/django/contrib/auth/models.py", line 141, in _create_user user.save(using=self._db) File "…/Vcs/django/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "…/Vcs/django/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "…/Vcs/django/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "…/Vcs/django/django/db/models/base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "…/Vcs/django/django/db/models/base.py", line 908, in _do_insert using=using, raw=raw) File "…/Vcs/django/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "…/Vcs/django/django/db/models/query.py", line 1175, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "…/Vcs/django/django/db/models/sql/compiler.py", line 1321, in execute_sql cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "…/Vcs/django/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/sqlite3/base.py", line 391, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: database is locked
This is only an issue when setting TEST["NAME"], but not NAME. The following works: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_tests_default.sqlite3', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_tests_other.sqlite3', } } Reproduced at 0dd2308cf6f559a4f4b50edd7c005c7cf025d1aa. Created ​PR Hey, I am able to replicate this bug and was able to fix it as well with the help of ​https://github.com/django/django/pull/11678, but the point I am stuck at is how to test it, I am not able to manipulate the cls variable so the next option that is left is create a file like test_sqlite and pass it as a parameter in runtests, should I be doing that? I think we should add tests/backends/sqlite/test_creation.py with regressions tests for test_db_signature(), you can take a look at tests/backends/base/test_creation.py with similar tests.
2019-11-20T17:49:06Z
3.1
["test_custom_test_name (backends.sqlite.test_creation.TestDbSignatureTests)"]
[]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-11283
08a4ee06510ae45562c228eefbdcaac84bd38c7a
diff --git a/django/contrib/auth/migrations/0011_update_proxy_permissions.py b/django/contrib/auth/migrations/0011_update_proxy_permissions.py --- a/django/contrib/auth/migrations/0011_update_proxy_permissions.py +++ b/django/contrib/auth/migrations/0011_update_proxy_permissions.py @@ -1,5 +1,18 @@ -from django.db import migrations +import sys + +from django.core.management.color import color_style +from django.db import migrations, transaction from django.db.models import Q +from django.db.utils import IntegrityError + +WARNING = """ + A problem arose migrating proxy model permissions for {old} to {new}. + + Permission(s) for {new} already existed. + Codenames Q: {query} + + Ensure to audit ALL permissions for {old} and {new}. +""" def update_proxy_model_permissions(apps, schema_editor, reverse=False): @@ -7,6 +20,7 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False): Update the content_type of proxy model permissions to use the ContentType of the proxy model. """ + style = color_style() Permission = apps.get_model('auth', 'Permission') ContentType = apps.get_model('contenttypes', 'ContentType') for Model in apps.get_models(): @@ -24,10 +38,16 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False): proxy_content_type = ContentType.objects.get_for_model(Model, for_concrete_model=False) old_content_type = proxy_content_type if reverse else concrete_content_type new_content_type = concrete_content_type if reverse else proxy_content_type - Permission.objects.filter( - permissions_query, - content_type=old_content_type, - ).update(content_type=new_content_type) + try: + with transaction.atomic(): + Permission.objects.filter( + permissions_query, + content_type=old_content_type, + ).update(content_type=new_content_type) + except IntegrityError: + old = '{}_{}'.format(old_content_type.app_label, old_content_type.model) + new = '{}_{}'.format(new_content_type.app_label, new_content_type.model) + sys.stdout.write(style.WARNING(WARNING.format(old=old, new=new, query=permissions_query))) def revert_proxy_model_permissions(apps, schema_editor):
diff --git a/tests/auth_tests/test_migrations.py b/tests/auth_tests/test_migrations.py --- a/tests/auth_tests/test_migrations.py +++ b/tests/auth_tests/test_migrations.py @@ -4,6 +4,7 @@ from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import TestCase +from django.test.utils import captured_stdout from .models import Proxy, UserProxy @@ -152,3 +153,27 @@ def test_user_keeps_same_permissions_after_migrating_backward(self): user = User._default_manager.get(pk=user.pk) for permission in [self.default_permission, self.custom_permission]: self.assertTrue(user.has_perm('auth_tests.' + permission.codename)) + + def test_migrate_with_existing_target_permission(self): + """ + Permissions may already exist: + + - Old workaround was to manually create permissions for proxy models. + - Model may have been concrete and then converted to proxy. + + Output a reminder to audit relevant permissions. + """ + proxy_model_content_type = ContentType.objects.get_for_model(Proxy, for_concrete_model=False) + Permission.objects.create( + content_type=proxy_model_content_type, + codename='add_proxy', + name='Can add proxy', + ) + Permission.objects.create( + content_type=proxy_model_content_type, + codename='display_proxys', + name='May display proxys information', + ) + with captured_stdout() as stdout: + update_proxy_permissions.update_proxy_model_permissions(apps, None) + self.assertIn('A problem arose migrating proxy model permissions', stdout.getvalue())
# Enhanced Problem Statement: Proxy Model Permission Migration Failure ## Issue Description When upgrading a Django project to version 2.2, the migration `auth.0011_update_proxy_permissions` fails with an integrity error when models have been recreated as proxy models. The error occurs because Django attempts to create permission entries in the `auth_permission` table that already exist, violating the unique constraint on `(content_type_id, codename)`. The specific error is: ``` django.db.utils.IntegrityError: duplicate key value violates unique constraint "idx_18141_auth_permission_content_type_id_01ab375a_uniq" DETAIL: Key (content_type_id, codename)=(12, add_agency) already exists. ``` This issue specifically affects proxy models where permissions might have already been created before the model was converted to a proxy model. The migration attempts to create new permissions without properly checking if equivalent permissions already exist in the database. ## Reproduction Steps 1. Create a Django project using Django 2.0 or 2.1. 2. Define a standard model in your application. 3. Run migrations to create the model and its associated permissions. 4. Later, modify the model to be a proxy model (add `class Meta: proxy = True`). 5. Attempt to upgrade to Django 2.2. 6. Run `python manage.py migrate` - the migration will fail at `auth.0011_update_proxy_permissions`. Internally, what happens is: 1. When the model was first created, Django created permission entries in the `auth_permission` table. 2. When the model was converted to a proxy model, new content types may have been created. 3. During the `auth.0011_update_proxy_permissions` migration, Django attempts to create permissions for proxy models. 4. The migration fails to check if equivalent permissions already exist, resulting in an attempt to create duplicate entries. 5. This violates the unique constraint on `(content_type_id, codename)`, causing the integrity error. ## Expected Behavior The migration should successfully complete without integrity errors. It should either: 1. Check for existing permissions before attempting to create new ones for proxy models. 2. Update existing permissions instead of creating new ones when a model has been converted to a proxy model. 3. Skip creating permissions that would violate the unique constraint. ## Exploration Hints ### Files to Examine: - `django/contrib/auth/migrations/0011_update_proxy_permissions.py` - This is the migration file causing the issue, which likely needs to check for existing permissions before creating new ones. - `django/contrib/auth/models.py` - Contains the `Permission` model that defines the unique constraint being violated. - `django/contrib/contenttypes/models.py` - The `ContentType` model and its manager handle how models (including proxy models) are identified in the permission system. - `django/db/migrations/operations/models.py` - Contains migration operations that handle model changes, including permission updates. ### Key Classes/Functions: - `Permission` model - Defines the schema for permissions with a unique constraint on `(content_type, codename)` that's being violated. - `ContentTypeManager.get_for_model()` - Handles retrieving content types for models, with special handling for proxy models via the `for_concrete_model` parameter. - `ContentType.model_class()` - Resolves ContentType objects back to their corresponding model classes. - Migration operations in `auth.0011_update_proxy_permissions` - Need to examine how they handle permission creation for proxy models. ### Areas of Interest: - The unique constraint on `(content_type_id, codename)` in the Permission model that's being violated. - How Django differentiates between original models and their proxy versions when creating permissions. - The caching system for ContentTypes which might retain references to previous model versions. - How the migration identifies which permissions to create for proxy models. ## Fix Hints ### High Confidence Locations: - The `auth.0011_update_proxy_permissions` migration file needs to be modified to check for existing permissions before attempting to create new ones. - The migration should detect when a model has been recreated as a proxy and handle permissions appropriately. ### Implementation Hints: - Before creating new permissions in the migration, query the database to check if permissions with the same codename already exist for the model. - Consider using `get_or_create()` instead of direct creation to avoid duplicate entries. - For proxy models, permissions might need to be transferred or updated rather than created anew. - Consider implementing a deduplication step before attempting to create new permissions. ### Alternative Hypotheses: - The issue could be in the ContentType system's handling of proxy models, which might not properly differentiate between an original model and its proxy version. - Database inconsistencies from previous migrations might exist if models were renamed or modified multiple times. - The way Django generates codenames for permissions might not account for model changes properly. - There could be an issue with how Django associates permissions with proxy models vs. their base models. - Custom permission handling in the user's application might be interfering with Django's built-in permission system.
Please provide a sample project or enough details to reproduce the issue. Same problem for me. If a Permission exists already with the new content_type and permission name, IntegrityError is raised since it violates the unique_key constraint on permission model i.e. content_type_id_code_name To get into the situation where you already have permissions with the content type you should be able to do the following: Start on Django <2.2 Create a model called 'TestModel' Migrate Delete the model called 'TestModel' Add a new proxy model called 'TestModel' Migrate Update to Django >=2.2 Migrate We think this is what happened in our case where we found this issue (​https://sentry.thalia.nu/share/issue/68be0f8c32764dec97855b3cbb3d8b55/). We have a proxy model with the same name that a previous non-proxy model once had. This changed during a refactor and the permissions + content type for the original model still exist. Our solution will probably be removing the existing permissions from the table, but that's really only a workaround. Reproduced with steps from comment. It's probably regression in 181fb60159e54d442d3610f4afba6f066a6dac05. What happens when creating a regular model, deleting it and creating a new proxy model: Create model 'RegularThenProxyModel' +----------------------------------+---------------------------+-----------------------+ | name | codename | model | +----------------------------------+---------------------------+-----------------------+ | Can add regular then proxy model | add_regularthenproxymodel | regularthenproxymodel | +----------------------------------+---------------------------+-----------------------+ Migrate Delete the model called 'RegularThenProxyModel' Add a new proxy model called 'RegularThenProxyModel' +----------------------------------+---------------------------+-----------------------+ | name | codename | model | +----------------------------------+---------------------------+-----------------------+ | Can add concrete model | add_concretemodel | concretemodel | | Can add regular then proxy model | add_regularthenproxymodel | concretemodel | | Can add regular then proxy model | add_regularthenproxymodel | regularthenproxymodel | +----------------------------------+---------------------------+-----------------------+ What happens when creating a proxy model right away: Create a proxy model 'RegularThenProxyModel' +----------------------------------+---------------------------+---------------+ | name | codename | model | +----------------------------------+---------------------------+---------------+ | Can add concrete model | add_concretemodel | concretemodel | | Can add regular then proxy model | add_regularthenproxymodel | concretemodel | +----------------------------------+---------------------------+---------------+ As you can see, the problem here is that permissions are not cleaned up, so we are left with an existing | Can add regular then proxy model | add_regularthenproxymodel | regularthenproxymodel | row. When the 2.2 migration is applied, it tries to create that exact same row, hence the IntegrityError. Unfortunately, there is no remove_stale_permission management command like the one for ContentType. So I think we can do one of the following: Show a nice error message to let the user delete the conflicting migration OR Re-use the existing permission I think 1. is much safer as it will force users to use a new permission and assign it accordingly to users/groups. Edit: I revised my initial comment after reproducing the error in my environment. It's also possible to get this kind of integrity error on the auth.0011 migration if another app is migrated first causing the auth post_migrations hook to run. The auth post migrations hook runs django.contrib.auth.management.create_permissions, which writes the new form of the auth_permission records to the table. Then when the auth.0011 migration runs it tries to update things to the values that were just written. To reproduce this behavior: pip install Django==2.1.7 Create an app, let's call it app, with two models, TestModel(models.Model) and ProxyModel(TestModel) the second one with proxy=True python manage.py makemigrations python manage.py migrate pip install Django==2.2 Add another model to app python manage.py makemigrations migrate the app only, python manage.py migrate app. This does not run the auth migrations, but does run the auth post_migrations hook Note that new records have been added to auth_permission python manage.py migrate, this causes an integrity error when the auth.0011 migration tries to update records that are the same as the ones already added in step 8. This has the same exception as this bug report, I don't know if it's considered a different bug, or the same one. Yes it is the same issue. My recommendation to let the users figure it out with a helpful message still stands even if it may sound a bit painful, because: It prevents data loss (we don't do an automatic delete/create of permissions) It prevents security oversights (we don't re-use an existing permission) It shouldn't happen for most use cases Again, I would love to hear some feedback or other alternatives. I won’t have time to work on this for the next 2 weeks so I’m de-assigning myself. I’ll pick it up again if nobody does and I’m available to discuss feedback/suggestions. I'll make a patch for this. I'll see about raising a suitable warning from the migration but we already warn in the release notes for this to audit permissions: my initial thought was that re-using the permission would be OK. (I see Arthur's comment. Other thoughts?) Being my first contribution I wanted to be super (super) careful with security concerns, but given the existing warning in the release notes for auditing prior to update, I agree that re-using the permission feels pretty safe and would remove overhead for people running into this scenario. Thanks for taking this on Carlton, I'd be happy to review.
2019-04-26T07:02:50Z
3.0
["test_migrate_with_existing_target_permission (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)"]
["test_migrate_backwards (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_proxy_model_permissions_contenttype (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_user_has_now_proxy_model_permissions (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_user_keeps_same_permissions_after_migrating_backward (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_migrate_backwards (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)", "test_proxy_model_permissions_contenttype (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)", "test_user_keeps_same_permissions_after_migrating_backward (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)", "test_user_still_has_proxy_model_permissions (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11630
65e86948b80262574058a94ccaae3a9b59c3faea
diff --git a/django/core/checks/model_checks.py b/django/core/checks/model_checks.py --- a/django/core/checks/model_checks.py +++ b/django/core/checks/model_checks.py @@ -4,7 +4,8 @@ from itertools import chain from django.apps import apps -from django.core.checks import Error, Tags, register +from django.conf import settings +from django.core.checks import Error, Tags, Warning, register @register(Tags.models) @@ -35,14 +36,25 @@ def check_all_models(app_configs=None, **kwargs): indexes[model_index.name].append(model._meta.label) for model_constraint in model._meta.constraints: constraints[model_constraint.name].append(model._meta.label) + if settings.DATABASE_ROUTERS: + error_class, error_id = Warning, 'models.W035' + error_hint = ( + 'You have configured settings.DATABASE_ROUTERS. Verify that %s ' + 'are correctly routed to separate databases.' + ) + else: + error_class, error_id = Error, 'models.E028' + error_hint = None for db_table, model_labels in db_table_models.items(): if len(model_labels) != 1: + model_labels_str = ', '.join(model_labels) errors.append( - Error( + error_class( "db_table '%s' is used by multiple models: %s." - % (db_table, ', '.join(db_table_models[db_table])), + % (db_table, model_labels_str), obj=db_table, - id='models.E028', + hint=(error_hint % model_labels_str) if error_hint else None, + id=error_id, ) ) for index_name, model_labels in indexes.items():
diff --git a/tests/check_framework/test_model_checks.py b/tests/check_framework/test_model_checks.py --- a/tests/check_framework/test_model_checks.py +++ b/tests/check_framework/test_model_checks.py @@ -1,12 +1,16 @@ from django.core import checks -from django.core.checks import Error +from django.core.checks import Error, Warning from django.db import models from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import ( - isolate_apps, modify_settings, override_system_checks, + isolate_apps, modify_settings, override_settings, override_system_checks, ) +class EmptyRouter: + pass + + @isolate_apps('check_framework', attr_name='apps') @override_system_checks([checks.model_checks.check_all_models]) class DuplicateDBTableTests(SimpleTestCase): @@ -28,6 +32,30 @@ class Meta: ) ]) + @override_settings(DATABASE_ROUTERS=['check_framework.test_model_checks.EmptyRouter']) + def test_collision_in_same_app_database_routers_installed(self): + class Model1(models.Model): + class Meta: + db_table = 'test_table' + + class Model2(models.Model): + class Meta: + db_table = 'test_table' + + self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ + Warning( + "db_table 'test_table' is used by multiple models: " + "check_framework.Model1, check_framework.Model2.", + hint=( + 'You have configured settings.DATABASE_ROUTERS. Verify ' + 'that check_framework.Model1, check_framework.Model2 are ' + 'correctly routed to separate databases.' + ), + obj='test_table', + id='models.W035', + ) + ]) + @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_collision_across_apps(self, apps): @@ -50,6 +78,34 @@ class Meta: ) ]) + @modify_settings(INSTALLED_APPS={'append': 'basic'}) + @override_settings(DATABASE_ROUTERS=['check_framework.test_model_checks.EmptyRouter']) + @isolate_apps('basic', 'check_framework', kwarg_name='apps') + def test_collision_across_apps_database_routers_installed(self, apps): + class Model1(models.Model): + class Meta: + app_label = 'basic' + db_table = 'test_table' + + class Model2(models.Model): + class Meta: + app_label = 'check_framework' + db_table = 'test_table' + + self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [ + Warning( + "db_table 'test_table' is used by multiple models: " + "basic.Model1, check_framework.Model2.", + hint=( + 'You have configured settings.DATABASE_ROUTERS. Verify ' + 'that basic.Model1, check_framework.Model2 are correctly ' + 'routed to separate databases.' + ), + obj='test_table', + id='models.W035', + ) + ]) + def test_no_collision_for_unmanaged_models(self): class Unmanaged(models.Model): class Meta:
Django throws error when different apps with different models have the same name table name. Description Error message: table_name: (models.E028) db_table 'table_name' is used by multiple models: base.ModelName, app2.ModelName. We have a Base app that points to a central database and that has its own tables. We then have multiple Apps that talk to their own databases. Some share the same table names. We have used this setup for a while, but after upgrading to Django 2.2 we're getting an error saying we're not allowed 2 apps, with 2 different models to have the same table names. Is this correct behavior? We've had to roll back to Django 2.0 for now.
Regression in [5d25804eaf81795c7d457e5a2a9f0b9b0989136c], ticket #20098. My opinion is that as soon as the project has a non-empty DATABASE_ROUTERS setting, the error should be turned into a warning, as it becomes difficult to say for sure that it's an error. And then the project can add the warning in SILENCED_SYSTEM_CHECKS. I agree with your opinion. Assigning to myself, patch on its way Replying to Claude Paroz: Regression in [5d25804eaf81795c7d457e5a2a9f0b9b0989136c], ticket #20098. My opinion is that as soon as the project has a non-empty DATABASE_ROUTERS setting, the error should be turned into a warning, as it becomes difficult to say for sure that it's an error. And then the project can add the warning in SILENCED_SYSTEM_CHECKS.
2019-08-05T11:22:41Z
3.0
["test_collision_across_apps_database_routers_installed (check_framework.test_model_checks.DuplicateDBTableTests)", "test_collision_in_same_app_database_routers_installed (check_framework.test_model_checks.DuplicateDBTableTests)"]
["test_collision_abstract_model (check_framework.test_model_checks.IndexNameTests)", "test_collision_across_apps (check_framework.test_model_checks.IndexNameTests)", "test_collision_in_different_models (check_framework.test_model_checks.IndexNameTests)", "test_collision_in_same_model (check_framework.test_model_checks.IndexNameTests)", "test_no_collision_abstract_model_interpolation (check_framework.test_model_checks.IndexNameTests)", "test_no_collision_across_apps_interpolation (check_framework.test_model_checks.IndexNameTests)", "test_collision_abstract_model (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_across_apps (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_in_different_models (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_in_same_model (check_framework.test_model_checks.ConstraintNameTests)", "test_no_collision_abstract_model_interpolation (check_framework.test_model_checks.ConstraintNameTests)", "test_no_collision_across_apps_interpolation (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_across_apps (check_framework.test_model_checks.DuplicateDBTableTests)", "test_collision_in_same_app (check_framework.test_model_checks.DuplicateDBTableTests)", "test_no_collision_for_proxy_models (check_framework.test_model_checks.DuplicateDBTableTests)", "test_no_collision_for_unmanaged_models (check_framework.test_model_checks.DuplicateDBTableTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11905
2f72480fbd27896c986c45193e1603e35c0b19a7
diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -1,5 +1,6 @@ import itertools import math +import warnings from copy import copy from django.core.exceptions import EmptyResultSet @@ -9,6 +10,7 @@ ) from django.db.models.query_utils import RegisterLookupMixin from django.utils.datastructures import OrderedSet +from django.utils.deprecation import RemovedInDjango40Warning from django.utils.functional import cached_property @@ -463,6 +465,17 @@ class IsNull(BuiltinLookup): prepare_rhs = False def as_sql(self, compiler, connection): + if not isinstance(self.rhs, bool): + # When the deprecation ends, replace with: + # raise ValueError( + # 'The QuerySet value for an isnull lookup must be True or ' + # 'False.' + # ) + warnings.warn( + 'Using a non-boolean value for an isnull lookup is ' + 'deprecated, use True or False instead.', + RemovedInDjango40Warning, + ) sql, params = compiler.compile(self.lhs) if self.rhs: return "%s IS NULL" % sql, params
diff --git a/tests/lookup/models.py b/tests/lookup/models.py --- a/tests/lookup/models.py +++ b/tests/lookup/models.py @@ -96,3 +96,15 @@ class Product(models.Model): class Stock(models.Model): product = models.ForeignKey(Product, models.CASCADE) qty_available = models.DecimalField(max_digits=6, decimal_places=2) + + +class Freebie(models.Model): + gift_product = models.ForeignKey(Product, models.CASCADE) + stock_id = models.IntegerField(blank=True, null=True) + + stock = models.ForeignObject( + Stock, + from_fields=['stock_id', 'gift_product'], + to_fields=['id', 'product'], + on_delete=models.CASCADE, + ) diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -9,9 +9,10 @@ from django.db.models.expressions import Exists, OuterRef from django.db.models.functions import Substr from django.test import TestCase, skipUnlessDBFeature +from django.utils.deprecation import RemovedInDjango40Warning from .models import ( - Article, Author, Game, IsNullWithNoneAsRHS, Player, Season, Tag, + Article, Author, Freebie, Game, IsNullWithNoneAsRHS, Player, Season, Tag, ) @@ -969,3 +970,24 @@ def test_exact_query_rhs_with_selected_columns(self): ).values('max_id') authors = Author.objects.filter(id=authors_max_ids[:1]) self.assertEqual(authors.get(), newest_author) + + def test_isnull_non_boolean_value(self): + # These tests will catch ValueError in Django 4.0 when using + # non-boolean values for an isnull lookup becomes forbidden. + # msg = ( + # 'The QuerySet value for an isnull lookup must be True or False.' + # ) + msg = ( + 'Using a non-boolean value for an isnull lookup is deprecated, ' + 'use True or False instead.' + ) + tests = [ + Author.objects.filter(alias__isnull=1), + Article.objects.filter(author__isnull=1), + Season.objects.filter(games__isnull=1), + Freebie.objects.filter(stock__isnull=1), + ] + for qs in tests: + with self.subTest(qs=qs): + with self.assertWarnsMessage(RemovedInDjango40Warning, msg): + qs.exists()
Prevent using __isnull lookup with non-boolean value. Description (last modified by Mariusz Felisiak) __isnull should not allow for non-boolean values. Using truthy/falsey doesn't promote INNER JOIN to an OUTER JOIN but works fine for a simple queries. Using non-boolean values is ​undocumented and untested. IMO we should raise an error for non-boolean values to avoid confusion and for consistency.
PR here: ​https://github.com/django/django/pull/11873 After the reconsideration I don't think that we should change this ​documented behavior (that is in Django from the very beginning). __isnull lookup expects boolean values in many places and IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples field__isnull='false' or field__isnull='true' (both would return the same result). You can always call bool() on a right hand side. Sorry for my previous acceptation (I shouldn't triage tickets in the weekend). Replying to felixxm: After the reconsideration I don't think that we should change this ​documented behavior (that is in Django from the very beginning). __isnull lookup expects boolean values in many places and IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples field__isnull='false' or field__isnull='true' (both would return the same result). You can always call bool() on a right hand side. Sorry for my previous acceptation (I shouldn't triage tickets in the weekend). I understand your point. But is there anything we can do to avoid people falling for the same pitfall I did? The problem, in my opinion, is that it works fine for simple queries but as soon as you add a join that needs promotion it will break, silently. Maybe we should make it raise an exception when a non-boolean is passed? One valid example is to have a class that implements __bool__. You can see here ​https://github.com/django/django/blob/d9881a025c15d87b2a7883ee50771117450ea90d/django/db/models/lookups.py#L465-L470 that non-bool value is converted to IS NULL and IS NOT NULL already using the truthy/falsy values. IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples fieldisnull='false' or fieldisnull='true' (both would return the same result). This is already the case. It just is inconsistent, in lookups.py field__isnull='false' will be a positive condition but on the query.py it will be the negative condition. Maybe adding a note on the documentation? something like: "Although it might seem like it will work with non-bool fields, this is not supported and can lead to inconsistent behaviours" Agreed, we should raise an error for non-boolean values, e.g. diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py index 9344979c56..fc4a38c4fe 100644 --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -463,6 +463,11 @@ class IsNull(BuiltinLookup): prepare_rhs = False def as_sql(self, compiler, connection): + if not isinstance(self.rhs, bool): + raise ValueError( + 'The QuerySet value for an isnull lookup must be True or ' + 'False.' + ) sql, params = compiler.compile(self.lhs) if self.rhs: return "%s IS NULL" % sql, params I changed the ticket description. Thanks, I'll work on it! Wouldn't that possibly break backward compatibility? I'm not familiar with how Django moves in that regard. We can add a release note in "Backwards incompatible changes" or deprecate this and remove in Django 4.0. I have to thing about it, please give me a day, maybe I will change my mind :) No problem. Thanks for taking the time to look into this! Another interesting example related to this: As an anecdote, I've also got bitten by this possibility. An attempt to write WHERE (field IS NULL) = boolean_field as .filter(field__isnull=F('boolean_field')) didn't go as I expected. Alexandr Aktsipetrov -- ​https://groups.google.com/forum/#!msg/django-developers/AhY2b3rxkfA/0sz3hNanCgAJ This example will generate the WHERE .... IS NULL. I guess we also would want an exception thrown here. André, IMO we should deprecate using non-boolean values in Django 3.1 (RemovedInDjango40Warning) and remove in Django 4.0 (even if it is untested and undocumented). I can imagine that a lot of people use e.g. 1 and 0 instead of booleans. Attached diff fixes also issue with passing a F() expression. def as_sql(self, compiler, connection): if not isinstance(self.rhs, bool): raise RemovedInDjango40Warning(...) .... Replying to felixxm: André, IMO we should deprecate using non-boolean values in Django 3.1 (RemovedInDjango40Warning) and remove in Django 4.0 (even if it is untested and undocumented). I can imagine that a lot of people use e.g. 1 and 0 instead of booleans. Attached diff fixes also issue with passing a F() expression. def as_sql(self, compiler, connection): if not isinstance(self.rhs, bool): raise RemovedInDjango40Warning(...) .... Sound like a good plan. Not super familiar with the branch structure of Django. So, I guess the path to follow is to make a PR to master adding the deprecation warning and eventually when master is 4.x we create the PR raising the ValueError. Is that right? Thanks! André, yes mostly. You can find more details about that ​from the documentation.
2019-10-11T18:19:39Z
3.1
["test_isnull_non_boolean_value (lookup.tests.LookupTests)", "test_iterator (lookup.tests.LookupTests)"]
["test_chain_date_time_lookups (lookup.tests.LookupTests)", "test_count (lookup.tests.LookupTests)", "test_custom_field_none_rhs (lookup.tests.LookupTests)", "Lookup.can_use_none_as_rhs=True allows None as a lookup value.", "test_error_messages (lookup.tests.LookupTests)", "test_escaping (lookup.tests.LookupTests)", "test_exact_exists (lookup.tests.LookupTests)", "Transforms are used for __exact=None.", "test_exact_query_rhs_with_selected_columns (lookup.tests.LookupTests)", "test_exact_sliced_queryset_limit_one (lookup.tests.LookupTests)", "test_exact_sliced_queryset_limit_one_offset (lookup.tests.LookupTests)", "test_exact_sliced_queryset_not_limited_to_one (lookup.tests.LookupTests)", "test_exclude (lookup.tests.LookupTests)", "test_exists (lookup.tests.LookupTests)", "test_get_next_previous_by (lookup.tests.LookupTests)", "test_in (lookup.tests.LookupTests)", "test_in_bulk (lookup.tests.LookupTests)", "test_in_bulk_lots_of_ids (lookup.tests.LookupTests)", "test_in_bulk_non_unique_field (lookup.tests.LookupTests)", "test_in_bulk_with_field (lookup.tests.LookupTests)", "test_in_different_database (lookup.tests.LookupTests)", "test_in_keeps_value_ordering (lookup.tests.LookupTests)", "test_lookup_collision (lookup.tests.LookupTests)", "test_lookup_date_as_str (lookup.tests.LookupTests)", "test_lookup_int_as_str (lookup.tests.LookupTests)", "test_nested_outerref_lhs (lookup.tests.LookupTests)", "test_none (lookup.tests.LookupTests)", "test_nonfield_lookups (lookup.tests.LookupTests)", "test_pattern_lookups_with_substr (lookup.tests.LookupTests)", "test_regex (lookup.tests.LookupTests)", "test_regex_backreferencing (lookup.tests.LookupTests)", "test_regex_non_ascii (lookup.tests.LookupTests)", "test_regex_non_string (lookup.tests.LookupTests)", "test_regex_null (lookup.tests.LookupTests)", "test_relation_nested_lookup_error (lookup.tests.LookupTests)", "test_unsupported_lookups (lookup.tests.LookupTests)", "test_values (lookup.tests.LookupTests)", "test_values_list (lookup.tests.LookupTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-11742
fee75d2aed4e58ada6567c464cfd22e89dc65f4a
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -257,6 +257,7 @@ def is_value(value, accept_promise=True): ) ] + choice_max_length = 0 # Expect [group_name, [value, display]] for choices_group in self.choices: try: @@ -270,16 +271,32 @@ def is_value(value, accept_promise=True): for value, human_name in group_choices ): break + if self.max_length is not None and group_choices: + choice_max_length = max( + choice_max_length, + *(len(value) for value, _ in group_choices if isinstance(value, str)), + ) except (TypeError, ValueError): # No groups, choices in the form [value, display] value, human_name = group_name, group_choices if not is_value(value) or not is_value(human_name): break + if self.max_length is not None and isinstance(value, str): + choice_max_length = max(choice_max_length, len(value)) # Special case: choices=['ab'] if isinstance(choices_group, str): break else: + if self.max_length is not None and choice_max_length > self.max_length: + return [ + checks.Error( + "'max_length' is too small to fit the longest value " + "in 'choices' (%d characters)." % choice_max_length, + obj=self, + id='fields.E009', + ), + ] return [] return [
diff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py --- a/tests/invalid_models_tests/test_ordinary_fields.py +++ b/tests/invalid_models_tests/test_ordinary_fields.py @@ -304,6 +304,32 @@ class Model(models.Model): self.assertEqual(Model._meta.get_field('field').check(), []) + def test_choices_in_max_length(self): + class Model(models.Model): + field = models.CharField( + max_length=2, choices=[ + ('ABC', 'Value Too Long!'), ('OK', 'Good') + ], + ) + group = models.CharField( + max_length=2, choices=[ + ('Nested', [('OK', 'Good'), ('Longer', 'Longer')]), + ('Grouped', [('Bad', 'Bad')]), + ], + ) + + for name, choice_max_length in (('field', 3), ('group', 6)): + with self.subTest(name): + field = Model._meta.get_field(name) + self.assertEqual(field.check(), [ + Error( + "'max_length' is too small to fit the longest value " + "in 'choices' (%d characters)." % choice_max_length, + obj=field, + id='fields.E009', + ), + ]) + def test_bad_db_index_value(self): class Model(models.Model): field = models.CharField(max_length=10, db_index='bad')
Add check to ensure max_length fits longest choice. Description There is currently no check to ensure that Field.max_length is large enough to fit the longest value in Field.choices. This would be very helpful as often this mistake is not noticed until an attempt is made to save a record with those values that are too long.
2019-09-04T08:30:14Z
3.0
["test_choices_in_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group (invalid_models_tests.test_ordinary_fields.CharFieldTests)"]
["test_non_nullable_blank (invalid_models_tests.test_ordinary_fields.GenericIPAddressFieldTests)", "test_forbidden_files_and_folders (invalid_models_tests.test_ordinary_fields.FilePathFieldTests)", "test_max_length_warning (invalid_models_tests.test_ordinary_fields.IntegerFieldTests)", "test_primary_key (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_upload_to_callable_not_checked (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_upload_to_starts_with_slash (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_valid_case (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_valid_default_case (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_str_default_value (invalid_models_tests.test_ordinary_fields.BinaryFieldTests)", "test_valid_default_value (invalid_models_tests.test_ordinary_fields.BinaryFieldTests)", "test_max_length_warning (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_primary_key (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_valid_case (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.DateTimeFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.DateTimeFieldTests)", "test_auto_now_and_auto_now_add_raise_error (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.TimeFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.TimeFieldTests)", "test_bad_values_of_max_digits_and_decimal_places (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_decimal_places_greater_than_max_digits (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_negative_max_digits_and_decimal_places (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_required_attributes (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_valid_field (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_bad_db_index_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_bad_max_length_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_bad_validators (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_containing_lazy (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_containing_non_pairs (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_bad_structure (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_lazy (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_non_pairs (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_iterable_of_iterable_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_lazy_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_missing_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_negative_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_non_iterable_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "Two letters isn't a valid choice pair.", "test_str_max_length_type (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_str_max_length_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_valid_field (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_pillow_installed (invalid_models_tests.test_ordinary_fields.ImageFieldTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11910
d232fd76a85870daf345fd8f8d617fe7802ae194
diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py --- a/django/db/migrations/autodetector.py +++ b/django/db/migrations/autodetector.py @@ -927,6 +927,10 @@ def generate_altered_fields(self): if remote_field_name: to_field_rename_key = rename_key + (remote_field_name,) if to_field_rename_key in self.renamed_fields: + # Repoint both model and field name because to_field + # inclusion in ForeignKey.deconstruct() is based on + # both. + new_field.remote_field.model = old_field.remote_field.model new_field.remote_field.field_name = old_field.remote_field.field_name # Handle ForeignObjects which can have multiple from_fields/to_fields. from_fields = getattr(new_field, 'from_fields', None)
diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py --- a/tests/migrations/test_autodetector.py +++ b/tests/migrations/test_autodetector.py @@ -932,6 +932,30 @@ def test_rename_foreign_object_fields(self): changes, 'app', 0, 1, model_name='bar', old_name='second', new_name='second_renamed', ) + def test_rename_referenced_primary_key(self): + before = [ + ModelState('app', 'Foo', [ + ('id', models.CharField(primary_key=True, serialize=False)), + ]), + ModelState('app', 'Bar', [ + ('id', models.AutoField(primary_key=True)), + ('foo', models.ForeignKey('app.Foo', models.CASCADE)), + ]), + ] + after = [ + ModelState('app', 'Foo', [ + ('renamed_id', models.CharField(primary_key=True, serialize=False)) + ]), + ModelState('app', 'Bar', [ + ('id', models.AutoField(primary_key=True)), + ('foo', models.ForeignKey('app.Foo', models.CASCADE)), + ]), + ] + changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True})) + self.assertNumberMigrations(changes, 'app', 1) + self.assertOperationTypes(changes, 'app', 0, ['RenameField']) + self.assertOperationAttributes(changes, 'app', 0, 0, old_name='id', new_name='renamed_id') + def test_rename_field_preserved_db_column(self): """ RenameField is used if a field is renamed and db_column equal to the
# ForeignKey `to_field` Not Updated When Renaming PrimaryKey Fields ## Issue Description When renaming a field that serves as a primary key using Django's migration system, foreign keys that explicitly reference this field via the `to_field` parameter continue to point to the old field name rather than updating to the new field name. This creates a disconnect between the model definition and the database schema, where the foreign key's `to_field` parameter contains a reference to a field name that no longer exists in the target model. This issue specifically occurs during the migration process when a `RenameField` operation is applied to a primary key field that is referenced by foreign keys from other models. ## Reproduction Steps ```python # Initial model definitions class ModelA(models.Model): field_wrong = models.CharField('field1', max_length=50, primary_key=True) class ModelB(models.Model): field_fk = models.ForeignKey(ModelA, blank=True, null=True, on_delete=models.CASCADE) # Apply initial migrations... # Modified model with renamed primary key class ModelA(models.Model): field_fixed = models.CharField('field1', max_length=50, primary_key=True) # Renamed from field_wrong class ModelB(models.Model): field_fk = models.ForeignKey(ModelA, blank=True, null=True, on_delete=models.CASCADE) # Generate migrations... ``` The resulting migration will correctly include a `RenameField` operation for ModelA's primary key, but any foreign keys pointing to this field will still reference `field_wrong` instead of `field_fixed` in their `to_field` parameter. This happens because: 1. Django's migration framework detects the field rename and generates a `RenameField` operation. 2. However, it fails to update references to this field in other models' foreign keys. 3. The `to_field` parameter in foreign keys is stored as a string literal in the migration files. 4. When migrations are applied, the foreign key still references a non-existent field name. ## Expected Behavior When a field that serves as a primary key is renamed, all foreign keys that reference it via `to_field` should be automatically updated to point to the new field name. The migration system should detect these dependencies and update all relevant references to maintain referential integrity. ## Exploration Hints ### Files to Examine: - **django/db/migrations/autodetector.py** - This file contains the `MigrationAutodetector` class which is responsible for detecting model changes and generating appropriate migration operations. The issue likely stems from this component not properly tracking field renames across model relationships. - **django/db/migrations/operations/fields.py** - Contains the `RenameField` operation class, which handles field renaming but appears to be missing logic to update references to the renamed field in other models. - **django/db/migrations/state.py** - Manages the `ProjectState` and `ModelState` classes that track the state of models during migration operations. The issue may involve how renamed fields are tracked in the state representation. - **django/db/models/fields/related.py** - Contains the `ForeignKey` class implementation, which stores and manages the `to_field` parameter. - **django/db/models/options.py** - Manages model metadata through the `Options` class, including field tracking and relationships. ### Key Classes/Functions: - **MigrationAutodetector._detect_field_renames()** - Responsible for detecting renamed fields; should analyze how it handles dependencies when primary keys are renamed. - **RenameField.state_forwards()** - Updates the Django model state when a field is renamed but doesn't appear to update references across models. - **ForeignKey.__init__() and ForeignKey.deconstruct()** - These methods handle how the `to_field` parameter is processed and serialized for migrations. - **ModelState.clone() and ModelState.rename_field()** - Handle field renaming in the model state but may not properly propagate changes to related models. ### Areas of Interest: - How Django's migration system tracks dependencies between models, especially with respect to field renames and foreign key references - The serialization and deserialization of `to_field` parameters in foreign keys during migration generation - How field references are tracked and updated across models when fields are renamed - The interaction between explicit `to_field` references and Django's default behavior of referencing primary keys ## Fix Hints ### High Confidence Locations: - **MigrationAutodetector._detect_changes()** or **_detect_field_renames()** - The fix likely involves modifying how field renames are detected and ensuring that foreign key references are updated accordingly. - **RenameField.state_forwards()** - This method needs to be enhanced to scan all models in the state for foreign keys referencing the renamed field and update their `to_field` parameters. ### Implementation Hints: - Add logic to the `RenameField` operation to track which primary key fields are being renamed. - When a primary key is renamed, scan all models in the project state for foreign keys referencing the renamed model. - For each foreign key found, check if its `to_field` parameter references the old field name and update it to the new name. - Ensure that this update happens in the same transaction as the field rename to maintain database integrity. - Consider adding a validation step that warns users about potentially broken foreign key references after field renames. ### Alternative Hypotheses: 1. The issue might involve how Django's ORM resolves field names at runtime versus how they're stored in migration files. There could be a disconnect between these two layers. 2. The problem might be related to the migration dependency resolution system, which might not correctly identify that foreign key references need to be updated when their target fields are renamed. 3. This could be an edge case specifically affecting primary keys that are explicitly referenced via `to_field`, as Django normally defaults to using the primary key without explicitly naming it. 4. There may be issues with how the model state is cached and refreshed during the migration detection process, causing outdated references to persist.
Thanks for this ticket. It looks like a regression in dcdd219ee1e062dc6189f382e0298e0adf5d5ddf, because an AlterField operation wasn't generated in such cases before this change (and I don't think we need it).
2019-10-14T01:56:49Z
3.1
["test_rename_referenced_primary_key (migrations.test_autodetector.AutodetectorTests)"]
["test_add_alter_order_with_respect_to (migrations.test_autodetector.AutodetectorTests)", "test_add_blank_textfield_and_charfield (migrations.test_autodetector.AutodetectorTests)", "Test change detection of new constraints.", "test_add_date_fields_with_auto_now_add_asking_for_default (migrations.test_autodetector.AutodetectorTests)", "test_add_date_fields_with_auto_now_add_not_asking_for_null_addition (migrations.test_autodetector.AutodetectorTests)", "test_add_date_fields_with_auto_now_not_asking_for_default (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of new fields.", "test_add_field_and_foo_together (migrations.test_autodetector.AutodetectorTests)", "#22030 - Adding a field with a default should work.", "Tests index/unique_together detection.", "Test change detection of new indexes.", "#22435 - Adding a ManyToManyField should not prompt for a default.", "test_add_model_order_with_respect_to (migrations.test_autodetector.AutodetectorTests)", "test_add_non_blank_textfield_and_charfield (migrations.test_autodetector.AutodetectorTests)", "Tests detection for adding db_table in model's options.", "Tests detection for changing db_table in model's options'.", "test_alter_db_table_no_changes (migrations.test_autodetector.AutodetectorTests)", "Tests detection for removing db_table in model's options.", "test_alter_db_table_with_model_change (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_fk_dependency_other_app (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_not_null_oneoff_default (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_not_null_with_default (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_not_null_without_default (migrations.test_autodetector.AutodetectorTests)", "test_alter_fk_before_model_deletion (migrations.test_autodetector.AutodetectorTests)", "test_alter_many_to_many (migrations.test_autodetector.AutodetectorTests)", "test_alter_model_managers (migrations.test_autodetector.AutodetectorTests)", "Changing a model's options should make a change.", "Changing a proxy model's options should also make a change.", "Tests auto-naming of migrations for graph matching.", "Bases of other models come first.", "test_circular_dependency_mixed_addcreate (migrations.test_autodetector.AutodetectorTests)", "test_circular_dependency_swappable (migrations.test_autodetector.AutodetectorTests)", "test_circular_dependency_swappable2 (migrations.test_autodetector.AutodetectorTests)", "test_circular_dependency_swappable_self (migrations.test_autodetector.AutodetectorTests)", "test_circular_fk_dependency (migrations.test_autodetector.AutodetectorTests)", "test_concrete_field_changed_to_many_to_many (migrations.test_autodetector.AutodetectorTests)", "test_create_model_and_unique_together (migrations.test_autodetector.AutodetectorTests)", "Test creation of new model with constraints already defined.", "Test creation of new model with indexes already defined.", "test_create_with_through_model (migrations.test_autodetector.AutodetectorTests)", "test_custom_deconstructible (migrations.test_autodetector.AutodetectorTests)", "Tests custom naming of migrations for graph matching.", "Field instances are handled correctly by nested deconstruction.", "test_deconstruct_type (migrations.test_autodetector.AutodetectorTests)", "Nested deconstruction descends into dict values.", "Nested deconstruction descends into lists.", "Nested deconstruction descends into tuples.", "test_default_related_name_option (migrations.test_autodetector.AutodetectorTests)", "test_different_regex_does_alter (migrations.test_autodetector.AutodetectorTests)", "test_empty_foo_together (migrations.test_autodetector.AutodetectorTests)", "test_first_dependency (migrations.test_autodetector.AutodetectorTests)", "Having a ForeignKey automatically adds a dependency.", "test_fk_dependency_other_app (migrations.test_autodetector.AutodetectorTests)", "test_foo_together_no_changes (migrations.test_autodetector.AutodetectorTests)", "test_foo_together_ordering (migrations.test_autodetector.AutodetectorTests)", "Tests unique_together and field removal detection & ordering", "test_foreign_key_removed_before_target_model (migrations.test_autodetector.AutodetectorTests)", "test_identical_regex_doesnt_alter (migrations.test_autodetector.AutodetectorTests)", "test_keep_db_table_with_model_change (migrations.test_autodetector.AutodetectorTests)", "test_last_dependency (migrations.test_autodetector.AutodetectorTests)", "test_m2m_w_through_multistep_remove (migrations.test_autodetector.AutodetectorTests)", "test_managed_to_unmanaged (migrations.test_autodetector.AutodetectorTests)", "test_many_to_many_changed_to_concrete_field (migrations.test_autodetector.AutodetectorTests)", "test_many_to_many_removed_before_through_model (migrations.test_autodetector.AutodetectorTests)", "test_many_to_many_removed_before_through_model_2 (migrations.test_autodetector.AutodetectorTests)", "test_mti_inheritance_model_removal (migrations.test_autodetector.AutodetectorTests)", "#23956 - Inheriting models doesn't move *_ptr fields into AddField operations.", "test_nested_deconstructible_objects (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of new models.", "test_non_circular_foreignkey_dependency_removal (migrations.test_autodetector.AutodetectorTests)", "Tests deletion of old models.", "Test change detection of reordering of fields in indexes.", "test_pk_fk_included (migrations.test_autodetector.AutodetectorTests)", "The autodetector correctly deals with proxy models.", "Bases of proxies come first.", "test_proxy_custom_pk (migrations.test_autodetector.AutodetectorTests)", "FK dependencies still work on proxy models.", "test_proxy_to_mti_with_fk_to_proxy (migrations.test_autodetector.AutodetectorTests)", "test_proxy_to_mti_with_fk_to_proxy_proxy (migrations.test_autodetector.AutodetectorTests)", "test_remove_alter_order_with_respect_to (migrations.test_autodetector.AutodetectorTests)", "Test change detection of removed constraints.", "Tests autodetection of removed fields.", "test_remove_field_and_foo_together (migrations.test_autodetector.AutodetectorTests)", "Test change detection of removed indexes.", "Tests autodetection of renamed fields.", "test_rename_field_and_foo_together (migrations.test_autodetector.AutodetectorTests)", "test_rename_field_foreign_key_to_field (migrations.test_autodetector.AutodetectorTests)", "test_rename_field_preserved_db_column (migrations.test_autodetector.AutodetectorTests)", "test_rename_foreign_object_fields (migrations.test_autodetector.AutodetectorTests)", "test_rename_m2m_through_model (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of renamed models.", "test_rename_model_reverse_relation_dependencies (migrations.test_autodetector.AutodetectorTests)", "test_rename_model_with_fks_in_different_position (migrations.test_autodetector.AutodetectorTests)", "test_rename_model_with_renamed_rel_field (migrations.test_autodetector.AutodetectorTests)", "test_rename_related_field_preserved_db_column (migrations.test_autodetector.AutodetectorTests)", "test_replace_string_with_foreignkey (migrations.test_autodetector.AutodetectorTests)", "test_same_app_circular_fk_dependency (migrations.test_autodetector.AutodetectorTests)", "test_same_app_circular_fk_dependency_with_unique_together_and_indexes (migrations.test_autodetector.AutodetectorTests)", "test_same_app_no_fk_dependency (migrations.test_autodetector.AutodetectorTests)", "Setting order_with_respect_to adds a field.", "test_supports_functools_partial (migrations.test_autodetector.AutodetectorTests)", "test_swappable (migrations.test_autodetector.AutodetectorTests)", "test_swappable_changed (migrations.test_autodetector.AutodetectorTests)", "test_swappable_circular_multi_mti (migrations.test_autodetector.AutodetectorTests)", "Swappable models get their CreateModel first.", "test_trim_apps (migrations.test_autodetector.AutodetectorTests)", "The autodetector correctly deals with managed models.", "test_unmanaged_custom_pk (migrations.test_autodetector.AutodetectorTests)", "test_unmanaged_delete (migrations.test_autodetector.AutodetectorTests)", "test_unmanaged_to_managed (migrations.test_autodetector.AutodetectorTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12286
979f61abd322507aafced9627702362e541ec34e
diff --git a/django/core/checks/translation.py b/django/core/checks/translation.py --- a/django/core/checks/translation.py +++ b/django/core/checks/translation.py @@ -1,4 +1,5 @@ from django.conf import settings +from django.utils.translation import get_supported_language_variant from django.utils.translation.trans_real import language_code_re from . import Error, Tags, register @@ -55,7 +56,9 @@ def check_setting_languages_bidi(app_configs, **kwargs): @register(Tags.translation) def check_language_settings_consistent(app_configs, **kwargs): """Error if language settings are not consistent with each other.""" - available_tags = {i for i, _ in settings.LANGUAGES} | {'en-us'} - if settings.LANGUAGE_CODE not in available_tags: + try: + get_supported_language_variant(settings.LANGUAGE_CODE) + except LookupError: return [E004] - return [] + else: + return []
diff --git a/tests/check_framework/test_translation.py b/tests/check_framework/test_translation.py --- a/tests/check_framework/test_translation.py +++ b/tests/check_framework/test_translation.py @@ -3,7 +3,7 @@ check_language_settings_consistent, check_setting_language_code, check_setting_languages, check_setting_languages_bidi, ) -from django.test import SimpleTestCase +from django.test import SimpleTestCase, override_settings class TranslationCheckTests(SimpleTestCase): @@ -75,12 +75,36 @@ def test_invalid_languages_bidi(self): Error(msg % tag, id='translation.E003'), ]) + @override_settings(USE_I18N=True, LANGUAGES=[('en', 'English')]) def test_inconsistent_language_settings(self): msg = ( 'You have provided a value for the LANGUAGE_CODE setting that is ' 'not in the LANGUAGES setting.' ) - with self.settings(LANGUAGE_CODE='fr', LANGUAGES=[('en', 'English')]): - self.assertEqual(check_language_settings_consistent(None), [ - Error(msg, id='translation.E004'), - ]) + for tag in ['fr', 'fr-CA', 'fr-357']: + with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): + self.assertEqual(check_language_settings_consistent(None), [ + Error(msg, id='translation.E004'), + ]) + + @override_settings( + USE_I18N=True, + LANGUAGES=[ + ('de', 'German'), + ('es', 'Spanish'), + ('fr', 'French'), + ('ca', 'Catalan'), + ], + ) + def test_valid_variant_consistent_language_settings(self): + tests = [ + # language + region. + 'fr-CA', + 'es-419', + 'de-at', + # language + region + variant. + 'ca-ES-valencia', + ] + for tag in tests: + with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): + self.assertEqual(check_language_settings_consistent(None), [])
# Enhanced Problem Statement: Django translation.E004 Error with Valid Language Sublanguages ## Issue Description Django's system check framework incorrectly raises `translation.E004` error when a sublanguage (e.g., "de-at") is specified in `LANGUAGE_CODE` setting, even though its base language (e.g., "de") is available. This behavior contradicts Django's documentation which states: "If a base language is available but the sublanguage specified is not, Django uses the base language." The issue stems from an inconsistency between runtime language resolution (which properly handles fallbacks to base languages) and system validation checks (which strictly require an exact match in the `LANGUAGES` setting). This affects Django 3.0.2 and potentially other versions. ## Reproduction Steps 1. Configure a Django project with the following in settings.py: ```python LANGUAGE_CODE = "de-at" # Austrian German ``` 2. Run Django with this configuration (e.g., `python manage.py runserver`) 3. The system will raise the following error: ``` SystemCheckError: System check identified some issues: ERRORS: ?: (translation.E004) You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting. ``` 4. If you instead use `LANGUAGE_CODE = "es-ar"` (which is included in Django's default translations), Django works fine. Internally, what's happening is: - The system check in `django/core/checks/translation.py` is strictly checking if `LANGUAGE_CODE` is in `available_tags` - It's not using the `get_supported_language_variant()` function which would properly handle the fallback to "de" - At runtime, Django would correctly use "de" when "de-at" is requested, but the validation check fails before runtime ## Expected Behavior The system check should not raise `translation.E004` when a sublanguage is specified in `LANGUAGE_CODE` if its base language is available in the `LANGUAGES` setting. This would align with Django's documented behavior and runtime language resolution logic. ## Exploration Hints ### Files to Examine: - **django/core/checks/translation.py** - Contains the system check that raises the error. The `check_language_settings_consistent` function specifically checks if `LANGUAGE_CODE` is in `available_tags` without considering base language fallbacks. - **django/utils/translation/trans_real.py** - Contains the `get_supported_language_variant()` function that properly handles language fallbacks at runtime but isn't being used during system checks. - **django/utils/translation/__init__.py** - Core translation functionality that might provide context on how language codes are processed. ### Key Classes/Functions: - **check_language_settings_consistent()** in django/core/checks/translation.py - The function that performs the validation causing the issue. It needs to be updated to support base language fallbacks. - **get_supported_language_variant()** in django/utils/translation/trans_real.py - Contains the logic for language fallbacks that should be used or mimicked in the system check. - **language_code_re** - Regular expression used to validate language code formats. ### Areas of Interest: - The logic used to extract base languages from sublanguages (e.g., "de" from "de-at") - How `settings.LANGUAGES` is populated and checked against during system checks - How language resolution differs between validation time and runtime - The difference in behavior between built-in language codes (like "es-ar") and custom ones (like "de-at") ## Fix Hints ### High Confidence Locations: - **django/core/checks/translation.py** - The `check_language_settings_consistent` function needs modification to account for base language fallbacks when validating `LANGUAGE_CODE`. ### Implementation Hints: - Modify the check to use or mimic `get_supported_language_variant()` from trans_real.py - When checking if `settings.LANGUAGE_CODE` is valid, extract the base language when dealing with a hyphenated code - Only raise the E004 error if neither the full language code nor its base language is in `available_tags` - A simple implementation might check if the base language (everything before the first hyphen) is in `available_tags` ### Alternative Hypotheses: - The issue might involve conflicts between how language files are discovered and loaded versus how language codes are validated - There could be an intentional design decision to be more strict during system checks than during runtime (though this would contradict documentation) - The problem might relate to the initialization timing of language settings, where checks happen before certain language-related structures are fully populated
Thanks for this report. Regression in 4400d8296d268f5a8523cd02ddc33b12219b2535.
2020-01-07T13:56:28Z
3.1
["test_valid_variant_consistent_language_settings (check_framework.test_translation.TranslationCheckTests)"]
["test_inconsistent_language_settings (check_framework.test_translation.TranslationCheckTests)", "test_invalid_language_code (check_framework.test_translation.TranslationCheckTests)", "test_invalid_languages (check_framework.test_translation.TranslationCheckTests)", "test_invalid_languages_bidi (check_framework.test_translation.TranslationCheckTests)", "test_valid_language_code (check_framework.test_translation.TranslationCheckTests)", "test_valid_languages (check_framework.test_translation.TranslationCheckTests)", "test_valid_languages_bidi (check_framework.test_translation.TranslationCheckTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12747
c86201b6ed4f8256b0a0520c08aa674f623d4127
diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py --- a/django/db/models/deletion.py +++ b/django/db/models/deletion.py @@ -408,7 +408,8 @@ def delete(self): # fast deletes for qs in self.fast_deletes: count = qs._raw_delete(using=self.using) - deleted_counter[qs.model._meta.label] += count + if count: + deleted_counter[qs.model._meta.label] += count # update fields for model, instances_for_fieldvalues in self.field_updates.items(): @@ -426,7 +427,8 @@ def delete(self): query = sql.DeleteQuery(model) pk_list = [obj.pk for obj in instances] count = query.delete_batch(pk_list, self.using) - deleted_counter[model._meta.label] += count + if count: + deleted_counter[model._meta.label] += count if not model._meta.auto_created: for obj in instances:
diff --git a/tests/delete/tests.py b/tests/delete/tests.py --- a/tests/delete/tests.py +++ b/tests/delete/tests.py @@ -522,11 +522,10 @@ def test_queryset_delete_returns_num_rows(self): existed_objs = { R._meta.label: R.objects.count(), HiddenUser._meta.label: HiddenUser.objects.count(), - A._meta.label: A.objects.count(), - MR._meta.label: MR.objects.count(), HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(), } deleted, deleted_objs = R.objects.all().delete() + self.assertCountEqual(deleted_objs.keys(), existed_objs.keys()) for k, v in existed_objs.items(): self.assertEqual(deleted_objs[k], v) @@ -550,13 +549,13 @@ def test_model_delete_returns_num_rows(self): existed_objs = { R._meta.label: R.objects.count(), HiddenUser._meta.label: HiddenUser.objects.count(), - A._meta.label: A.objects.count(), MR._meta.label: MR.objects.count(), HiddenUserProfile._meta.label: HiddenUserProfile.objects.count(), M.m2m.through._meta.label: M.m2m.through.objects.count(), } deleted, deleted_objs = r.delete() self.assertEqual(deleted, sum(existed_objs.values())) + self.assertCountEqual(deleted_objs.keys(), existed_objs.keys()) for k, v in existed_objs.items(): self.assertEqual(deleted_objs[k], v) @@ -694,7 +693,7 @@ def test_fast_delete_empty_no_update_can_self_select(self): with self.assertNumQueries(1): self.assertEqual( User.objects.filter(avatar__desc='missing').delete(), - (0, {'delete.User': 0}) + (0, {}), ) def test_fast_delete_combined_relationships(self):
# QuerySet.Delete: Inconsistent Results When Zero Objects Deleted ## Issue Description The `QuerySet.delete()` method returns inconsistent results when no objects are deleted. This method returns a tuple `(total_count, model_counts)`, where `total_count` is the total number of deleted objects (including cascaded deletions) and `model_counts` is a dictionary mapping model labels to deletion counts. The inconsistency occurs when zero objects are deleted: - For models with foreign keys: `(0, {})` - For "simple" models without foreign keys: `(0, {'my_app.ModelName': 0})` This inconsistent behavior complicates error handling and creates unpredictable API responses for consumers. ## Reproduction Steps ```python # For a model with foreign keys related_objects = RelatedModel.objects.filter(id=-999) # Non-existent ID result = related_objects.delete() print(result) # Output: (0, {}) # For a "simple" model without foreign keys simple_objects = SimpleModel.objects.filter(id=-999) # Non-existent ID result = simple_objects.delete() print(result) # Output: (0, {'app_name.SimpleModel': 0}) ``` Internally, the issue arises from how the Django deletion collector handles different model types. For models with foreign keys, the collector uses cascading deletion machinery which may not add the model to the tracking dictionary when no objects exist. For simple models, the model is tracked with a zero count even when no objects are found. ## Expected Behavior The return value format should be consistent regardless of model type. Either: 1. Both cases should return `(0, {})` when no objects are deleted, OR 2. Both cases should return `(0, {'app_name.ModelName': 0})`, including the model in the dictionary with a zero count The second approach is likely better for API consumers as it always includes the model in the result, making the return format more predictable. ## Exploration Hints ### Files to Examine: - **django/db/models/query.py** - Contains the `QuerySet` class with the `delete()` method that returns the inconsistent tuple. This method delegates to a collector that gathers and performs deletions. - **django/db/models/deletion.py** - Contains the `Collector` class responsible for tracking objects by model type and performing deletions. The inconsistency likely originates in how this class builds the result dictionary. ### Key Classes/Functions: - **QuerySet.delete()** - The public method that exhibits the inconsistent behavior. Calls `Collector.delete()` and returns its result. - **QuerySet._raw_delete()** - Called by `delete()`, this may handle some model-specific logic. - **Collector.delete()** - Orchestrates deletion and builds the result tuple. The inconsistency likely originates here in how it tracks deletions by model type. - **Collector.collect()** - Gathers objects for deletion, including cascaded deletes for related objects. ### Areas of Interest: - How the `data_objs` dictionary in the `Collector` class is populated during collection and deletion - The conditions under which model labels are added to or excluded from the result dictionary - Different code paths for models with relationships versus simple models - How deletion counts are tracked and reported in the final result tuple ## Fix Hints ### High Confidence Locations: - `Collector.delete()` in django/db/models/deletion.py is the most likely fix location. This method constructs the result tuple and dictionary that shows the inconsistent behavior. ### Implementation Hints: 1. The fix likely involves normalizing how models are tracked in the deletion process: - Always add the model to the result dictionary, even if the count is zero, OR - Never add models with zero deletions to the dictionary 2. A simple approach might be to ensure the collector consistently initializes the count for the primary model being deleted, even when no objects are found. 3. The fix should be careful to preserve the existing behavior for cases where objects are actually deleted. ### Alternative Hypotheses: 1. The issue might originate in how `QuerySet.delete()` calls `Collector.delete()` rather than in the `Collector` itself. 2. The inconsistency could be in the collection phase rather than the deletion phase - objects for simple models might always be "collected" (even if none exist) while related models are only collected if they actually exist. 3. There could be optimization logic that skips certain steps for models with foreign keys when no objects are found, resulting in different dictionary construction. 4. The behavior might be related to how SQL queries are constructed and their results processed differently for different model types.
I guess we could adapt the code not to include any key if the count is zero in the second case.
2020-04-18T16:41:40Z
3.1
["test_fast_delete_empty_no_update_can_self_select (delete.tests.FastDeleteTests)", "test_model_delete_returns_num_rows (delete.tests.DeletionTests)", "test_queryset_delete_returns_num_rows (delete.tests.DeletionTests)"]
["test_fast_delete_combined_relationships (delete.tests.FastDeleteTests)", "test_fast_delete_fk (delete.tests.FastDeleteTests)", "test_fast_delete_inheritance (delete.tests.FastDeleteTests)", "test_fast_delete_instance_set_pk_none (delete.tests.FastDeleteTests)", "test_fast_delete_joined_qs (delete.tests.FastDeleteTests)", "test_fast_delete_large_batch (delete.tests.FastDeleteTests)", "test_fast_delete_m2m (delete.tests.FastDeleteTests)", "test_fast_delete_qs (delete.tests.FastDeleteTests)", "test_fast_delete_revm2m (delete.tests.FastDeleteTests)", "test_auto (delete.tests.OnDeleteTests)", "test_auto_nullable (delete.tests.OnDeleteTests)", "test_cascade (delete.tests.OnDeleteTests)", "test_cascade_from_child (delete.tests.OnDeleteTests)", "test_cascade_from_parent (delete.tests.OnDeleteTests)", "test_cascade_nullable (delete.tests.OnDeleteTests)", "test_do_nothing (delete.tests.OnDeleteTests)", "test_do_nothing_qscount (delete.tests.OnDeleteTests)", "test_inheritance_cascade_down (delete.tests.OnDeleteTests)", "test_inheritance_cascade_up (delete.tests.OnDeleteTests)", "test_non_callable (delete.tests.OnDeleteTests)", "test_o2o_setnull (delete.tests.OnDeleteTests)", "test_protect (delete.tests.OnDeleteTests)", "test_protect_multiple (delete.tests.OnDeleteTests)", "test_protect_path (delete.tests.OnDeleteTests)", "test_restrict (delete.tests.OnDeleteTests)", "test_restrict_gfk_no_fast_delete (delete.tests.OnDeleteTests)", "test_restrict_multiple (delete.tests.OnDeleteTests)", "test_restrict_path_cascade_direct (delete.tests.OnDeleteTests)", "test_restrict_path_cascade_indirect (delete.tests.OnDeleteTests)", "test_restrict_path_cascade_indirect_diamond (delete.tests.OnDeleteTests)", "test_setdefault (delete.tests.OnDeleteTests)", "test_setdefault_none (delete.tests.OnDeleteTests)", "test_setnull (delete.tests.OnDeleteTests)", "test_setnull_from_child (delete.tests.OnDeleteTests)", "test_setnull_from_parent (delete.tests.OnDeleteTests)", "test_setvalue (delete.tests.OnDeleteTests)", "test_bulk (delete.tests.DeletionTests)", "test_can_defer_constraint_checks (delete.tests.DeletionTests)", "test_delete_with_keeping_parents (delete.tests.DeletionTests)", "test_delete_with_keeping_parents_relationships (delete.tests.DeletionTests)", "test_deletion_order (delete.tests.DeletionTests)", "test_hidden_related (delete.tests.DeletionTests)", "test_instance_update (delete.tests.DeletionTests)", "test_large_delete (delete.tests.DeletionTests)", "test_large_delete_related (delete.tests.DeletionTests)", "test_m2m (delete.tests.DeletionTests)", "test_only_referenced_fields_selected (delete.tests.DeletionTests)", "test_proxied_model_duplicate_queries (delete.tests.DeletionTests)", "test_relational_post_delete_signals_happen_before_parent_object (delete.tests.DeletionTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-13768
965d2d95c630939b53eb60d9c169f5dfc77ee0c6
diff --git a/django/dispatch/dispatcher.py b/django/dispatch/dispatcher.py --- a/django/dispatch/dispatcher.py +++ b/django/dispatch/dispatcher.py @@ -1,3 +1,4 @@ +import logging import threading import warnings import weakref @@ -5,6 +6,8 @@ from django.utils.deprecation import RemovedInDjango40Warning from django.utils.inspect import func_accepts_kwargs +logger = logging.getLogger('django.dispatch') + def _make_id(target): if hasattr(target, '__func__'): @@ -208,6 +211,12 @@ def send_robust(self, sender, **named): try: response = receiver(signal=self, sender=sender, **named) except Exception as err: + logger.error( + 'Error calling %s in Signal.send_robust() (%s)', + receiver.__qualname__, + err, + exc_info=err, + ) responses.append((receiver, err)) else: responses.append((receiver, response))
diff --git a/tests/dispatch/tests.py b/tests/dispatch/tests.py --- a/tests/dispatch/tests.py +++ b/tests/dispatch/tests.py @@ -165,13 +165,28 @@ def test_send_robust_fail(self): def fails(val, **kwargs): raise ValueError('this') a_signal.connect(fails) - result = a_signal.send_robust(sender=self, val="test") - err = result[0][1] - self.assertIsInstance(err, ValueError) - self.assertEqual(err.args, ('this',)) - self.assertTrue(hasattr(err, '__traceback__')) - self.assertIsInstance(err.__traceback__, TracebackType) - a_signal.disconnect(fails) + try: + with self.assertLogs('django.dispatch', 'ERROR') as cm: + result = a_signal.send_robust(sender=self, val='test') + err = result[0][1] + self.assertIsInstance(err, ValueError) + self.assertEqual(err.args, ('this',)) + self.assertIs(hasattr(err, '__traceback__'), True) + self.assertIsInstance(err.__traceback__, TracebackType) + + log_record = cm.records[0] + self.assertEqual( + log_record.getMessage(), + 'Error calling ' + 'DispatcherTests.test_send_robust_fail.<locals>.fails in ' + 'Signal.send_robust() (this)', + ) + self.assertIsNotNone(log_record.exc_info) + _, exc_value, _ = log_record.exc_info + self.assertIsInstance(exc_value, ValueError) + self.assertEqual(str(exc_value), 'this') + finally: + a_signal.disconnect(fails) self.assertTestIsClean(a_signal) def test_disconnection(self):
# Enhanced Problem Statement: Signal Exception Logging ## Issue Description Django's `Signal.send_robust()` method silently catches exceptions raised in signal receivers without logging them, contrary to Django's usual practice of logging exceptions in similar situations (such as missing template variables). This creates a debugging blind spot where errors in signal handlers go unnoticed unless the caller explicitly checks the return values. This lack of visibility is particularly problematic for error monitoring tools like Sentry that rely on logs to capture and report issues in production environments. The issue requires adding logging capabilities to the exception handling in `send_robust()` while maintaining its current behavior of continuing execution after receiver exceptions. ## Reproduction Steps 1. Create a Django signal: ```python from django.dispatch import Signal my_signal = Signal() ``` 2. Register a receiver that raises an exception: ```python @my_signal.connect def failing_receiver(sender, **kwargs): raise ValueError("Test exception in signal receiver") ``` 3. Call `send_robust()` on the signal: ```python results = my_signal.send_robust(sender=None) ``` 4. Observe that the exception is caught and returned in the results, but nothing is logged: ```python for receiver, response in results: if isinstance(response, Exception): print(f"Exception occurred in {receiver}: {response}") ``` Internally, `send_robust()` catches exceptions in a `try/except Exception` block but doesn't use Django's logging framework to record these exceptions, making them invisible to error tracking systems unless explicitly processed by the caller. ## Expected Behavior When an exception occurs in a signal receiver during `send_robust()` execution: 1. The exception should be logged using `logger.exception()` to capture the full traceback 2. The current behavior of catching the exception and continuing execution should be preserved 3. The return value format (a list of (receiver, response) tuples) should remain unchanged 4. The exception should still be included in the return value as it is now This would align with Django's approach in other areas where exceptions are logged for visibility while allowing execution to continue. ## Exploration Hints ### Files to Examine: - **django/dispatch/dispatcher.py** - Contains the core implementation of Django's signal dispatch system, particularly the `Signal` class with its `send_robust()` method. This is the primary file where changes will be needed. ### Key Classes/Functions: - **Signal.send_robust()** - The method that catches exceptions from signal receivers but doesn't log them. This method returns a list of (receiver, response) tuples where response can be either the return value or an exception instance. The method's exception handling block needs modification to add logging. ### Areas of Interest: - The exception handling in `send_robust()` likely has a structure similar to: ```python try: response = receiver(signal=self, sender=sender, **named) except Exception as err: response = err ``` - The logging implementation should preserve the exception context to ensure stacktraces are properly captured - Django's logging conventions should be followed (likely using `logging.getLogger(__name__)`) ## Fix Hints ### High Confidence Locations: - The `except Exception as err:` block in the `send_robust()` method is where logging should be added while keeping the existing behavior of assigning the exception to `response`. ### Implementation Hints: - Import the logging module at the top of the file: `import logging` - Create a logger instance: `logger = logging.getLogger(__name__)` - Add a logging statement in the exception block: ```python except Exception as err: logger.exception("Exception raised by %s when handling '%s' signal", receiver_object, self.name) response = err ``` - Ensure the log message includes context about which receiver failed and for what signal - The logging level should be ERROR since this represents an unhandled exception in user code ### Alternative Hypotheses: - There may be performance concerns if signals with many receivers frequently encounter exceptions, resulting in excessive logging. If this becomes an issue, a configurable logging threshold or rate limiting could be considered. - Some users might rely on the current silent behavior. Adding logging changes the side effects of the method, though not its return values. Consider whether this would be a backward-incompatible change in practice. - There might be value in adding a parameter to control whether exceptions are logged (e.g., `log_exceptions=True`), allowing users to maintain the current behavior if desired.
I would like to work on this issue. PS. i am new to this django. so any advice would be appreciated
2020-12-12T07:34:48Z
3.2
["test_send_robust_fail (dispatch.tests.DispatcherTests)"]
["test_receiver_signal_list (dispatch.tests.ReceiverTestCase)", "test_receiver_single_signal (dispatch.tests.ReceiverTestCase)", "test_cached_garbaged_collected (dispatch.tests.DispatcherTests)", "test_cannot_connect_no_kwargs (dispatch.tests.DispatcherTests)", "test_cannot_connect_non_callable (dispatch.tests.DispatcherTests)", "test_disconnection (dispatch.tests.DispatcherTests)", "test_garbage_collected (dispatch.tests.DispatcherTests)", "test_has_listeners (dispatch.tests.DispatcherTests)", "test_multiple_registration (dispatch.tests.DispatcherTests)", "test_send (dispatch.tests.DispatcherTests)", "test_send_connected_no_sender (dispatch.tests.DispatcherTests)", "test_send_different_no_sender (dispatch.tests.DispatcherTests)", "test_send_no_receivers (dispatch.tests.DispatcherTests)", "test_send_robust_ignored_sender (dispatch.tests.DispatcherTests)", "test_send_robust_no_receivers (dispatch.tests.DispatcherTests)", "test_send_robust_success (dispatch.tests.DispatcherTests)", "test_uid_registration (dispatch.tests.DispatcherTests)", "test_values_returned_by_disconnection (dispatch.tests.DispatcherTests)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django/django
django__django-12708
447980e72ac01da1594dd3373a03ba40b7ee6f80
diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py --- a/django/db/backends/base/schema.py +++ b/django/db/backends/base/schema.py @@ -393,7 +393,12 @@ def alter_index_together(self, model, old_index_together, new_index_together): news = {tuple(fields) for fields in new_index_together} # Deleted indexes for fields in olds.difference(news): - self._delete_composed_index(model, fields, {'index': True}, self.sql_delete_index) + self._delete_composed_index( + model, + fields, + {'index': True, 'unique': False}, + self.sql_delete_index, + ) # Created indexes for field_names in news.difference(olds): fields = [model._meta.get_field(field) for field in field_names]
diff --git a/tests/migrations/test_base.py b/tests/migrations/test_base.py --- a/tests/migrations/test_base.py +++ b/tests/migrations/test_base.py @@ -62,7 +62,11 @@ def assertIndexExists(self, table, columns, value=True, using='default', index_t any( c["index"] for c in connections[using].introspection.get_constraints(cursor, table).values() - if c['columns'] == list(columns) and (index_type is None or c['type'] == index_type) + if ( + c['columns'] == list(columns) and + (index_type is None or c['type'] == index_type) and + not c['unique'] + ) ), ) @@ -80,6 +84,14 @@ def assertConstraintExists(self, table, name, value=True, using='default'): def assertConstraintNotExists(self, table, name): return self.assertConstraintExists(table, name, False) + def assertUniqueConstraintExists(self, table, columns, value=True, using='default'): + with connections[using].cursor() as cursor: + constraints = connections[using].introspection.get_constraints(cursor, table).values() + self.assertEqual( + value, + any(c['unique'] for c in constraints if c['columns'] == list(columns)), + ) + def assertFKExists(self, table, columns, to, value=True, using='default'): with connections[using].cursor() as cursor: self.assertEqual( diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py --- a/tests/migrations/test_operations.py +++ b/tests/migrations/test_operations.py @@ -1759,6 +1759,29 @@ def test_alter_index_together_remove(self): operation = migrations.AlterIndexTogether("Pony", None) self.assertEqual(operation.describe(), "Alter index_together for Pony (0 constraint(s))") + @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields') + def test_alter_index_together_remove_with_unique_together(self): + app_label = 'test_alintoremove_wunto' + table_name = '%s_pony' % app_label + project_state = self.set_up_test_model(app_label, unique_together=True) + self.assertUniqueConstraintExists(table_name, ['pink', 'weight']) + # Add index together. + new_state = project_state.clone() + operation = migrations.AlterIndexTogether('Pony', [('pink', 'weight')]) + operation.state_forwards(app_label, new_state) + with connection.schema_editor() as editor: + operation.database_forwards(app_label, editor, project_state, new_state) + self.assertIndexExists(table_name, ['pink', 'weight']) + # Remove index together. + project_state = new_state + new_state = project_state.clone() + operation = migrations.AlterIndexTogether('Pony', set()) + operation.state_forwards(app_label, new_state) + with connection.schema_editor() as editor: + operation.database_forwards(app_label, editor, project_state, new_state) + self.assertIndexNotExists(table_name, ['pink', 'weight']) + self.assertUniqueConstraintExists(table_name, ['pink', 'weight']) + @skipUnlessDBFeature('supports_table_check_constraints') def test_add_constraint(self): project_state = self.set_up_test_model("test_addconstraint")
# Migration Crashes When Deleting index_together with Overlapping unique_together ## Issue Description In Django 1.11.10, there's a critical issue when attempting to delete an `index_together` constraint that shares the same fields with a `unique_together` constraint. The migration system fails to distinguish between these two types of constraints when they cover the same database columns. The issue manifests as a `ValueError` with the message "Found wrong number (2) of constraints" in the `_delete_composed_index()` method of Django's schema editor. This occurs because the schema editor identifies both the unique constraint and the index constraint when trying to delete just the index, and it doesn't have logic to determine which one to remove. This problem particularly affects users who are trying to refactor their code to use Django 1.11's newer `Options.indexes` feature instead of the legacy `index_together` approach. In such cases, even though users are just changing the declaration method (not actually removing the index functionality), Django attempts to delete and recreate the index during migration, causing the error. ## Reproduction Steps 1. Create models with 2 fields that are included in both `unique_together` and `index_together`: ```python class MyModel(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=100) class Meta: unique_together = (('field1', 'field2'),) index_together = (('field1', 'field2'),) ``` 2. Create and apply initial migration to set up the model with both constraints 3. Update the model to remove the `index_together` constraint (but keep the `unique_together`): ```python class MyModel(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=100) class Meta: unique_together = (('field1', 'field2'),) # index_together removed ``` 4. Attempt to create and apply migration 5. The migration will fail with a `ValueError: Found wrong number (2) of constraints` error at `django/db/backends/base/schema.py`, line 378, in the `_delete_composed_index()` method. What happens internally: - The migration system correctly detects the removal of the `index_together` constraint - It attempts to identify and delete the corresponding database index - When querying the database for constraints on these fields, it finds two: one from `unique_together` (which creates a unique index) and one from `index_together` - The `_delete_composed_index()` method expects to find exactly one constraint, causing it to raise the error ## Expected Behavior Django should be able to: 1. Properly identify which constraint to delete when `index_together` and `unique_together` overlap 2. Successfully delete only the index constraint while preserving the unique constraint 3. Allow smooth transition from `index_together` to `Options.indexes` without requiring deletion and recreation of indexes ## Exploration Hints ### Files to Examine: - **django/db/backends/base/schema.py** - Contains the `_delete_composed_index()` method where the error occurs (line 378). This method is failing to distinguish between unique constraints and regular indexes when they cover the same fields. - **django/db/models/options.py** - Contains the `Options` class that handles both `unique_together` and `index_together` attributes. The issue occurs at the intersection of these two features, and this file defines how they're processed. - **django/db/migrations/operations/models.py** - Contains the `AlterUniqueTogether` and `AlterIndexTogether` operations, which handle these model changes during migrations. - **django/db/backends/base/introspection.py** - Provides the `get_constraints()` method that's used to identify database constraints, which is crucial to understanding how Django identifies what to delete. ### Key Classes/Functions: - **SchemaEditor._delete_composed_index()** - Responsible for deleting composite indexes; fails when it finds both a unique constraint and an index constraint on the same fields. - **Options.normalize_together()** - Normalizes both `unique_together` and `index_together` declarations, possibly not providing enough differentiation for deletion operations. - **AlterIndexTogether.database_forwards()/database_backwards()** - Methods that translate model changes to schema operations; may need to better handle overlaps with `unique_together`. - **BaseDatabaseIntrospection.get_constraints()** - The abstract method implemented by database backends to identify existing constraints; may not provide sufficient information to distinguish between constraint types. ### Areas of Interest: - Constraint naming patterns and how they might lead to ambiguity - How Django differentiates between unique constraints and regular indexes - The process of transitioning from `index_together` to `Options.indexes` and why it involves index deletion - Database-specific behaviors regarding unique constraints and their implicit indexes ## Fix Hints ### High Confidence Locations: - **SchemaEditor._delete_composed_index()** in django/db/backends/base/schema.py - This is the most likely fix location as it's where the error is raised. The method needs to be updated to handle cases where multiple constraints (both unique and index) exist on the same fields. ### Implementation Hints: - Modify `_delete_composed_index()` to filter constraints by type (unique vs. index) when identifying which one to delete - Add a parameter to the function to specify whether to target only indexes or only unique constraints - Consider enhancing the constraint identification logic to use additional metadata beyond just field names - For the refactoring use case (moving from `index_together` to `Options.indexes`), consider adding detection logic that avoids unnecessary index deletion and recreation ### Alternative Hypotheses: - The issue might be database-specific, with different database backends handling composite indexes differently - The constraint naming convention might be inconsistent, making it impossible to reliably distinguish between constraint types - There could be a deeper architectural issue in how Django tracks the "purpose" or "origin" of database constraints throughout their lifecycle - The migration framework may need broader changes to correctly track which constraints were created by which model declaration methods
Reproduced on master at 623139b5d1bd006eac78b375bcaf5948e695c3c6. I haven't looked under the hood on this yet, but could it be related to the ordering of the operations generated for the mgiration? on first inspection it feels like this and #28862 could be caused by the same/similar underlying problem in how FieldRelatedOptionOperation subclasses ordering is handled in the migration autodetector's migration optimizer.
2020-04-12T22:20:59Z
3.1
["test_alter_index_together_remove_with_unique_together (migrations.test_operations.OperationTests)"]
["test_references_model_mixin (migrations.test_operations.TestCreateModel)", "test_reference_field_by_through_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_from_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_name (migrations.test_operations.FieldOperationTests)", "test_references_field_by_remote_field_model (migrations.test_operations.FieldOperationTests)", "test_references_field_by_through (migrations.test_operations.FieldOperationTests)", "test_references_field_by_to_fields (migrations.test_operations.FieldOperationTests)", "test_references_model (migrations.test_operations.FieldOperationTests)", "test_add_field_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_create_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_delete_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_indexes_ignore_swapped (migrations.test_operations.SwappableOperationTests)", "test_add_binaryfield (migrations.test_operations.OperationTests)", "test_add_charfield (migrations.test_operations.OperationTests)", "test_add_constraint (migrations.test_operations.OperationTests)", "test_add_constraint_combinable (migrations.test_operations.OperationTests)", "test_add_constraint_percent_escaping (migrations.test_operations.OperationTests)", "test_add_field (migrations.test_operations.OperationTests)", "test_add_field_m2m (migrations.test_operations.OperationTests)", "test_add_field_preserve_default (migrations.test_operations.OperationTests)", "test_add_index (migrations.test_operations.OperationTests)", "test_add_index_state_forwards (migrations.test_operations.OperationTests)", "test_add_or_constraint (migrations.test_operations.OperationTests)", "test_add_partial_unique_constraint (migrations.test_operations.OperationTests)", "test_add_textfield (migrations.test_operations.OperationTests)", "test_alter_field (migrations.test_operations.OperationTests)", "test_alter_field_m2m (migrations.test_operations.OperationTests)", "test_alter_field_pk (migrations.test_operations.OperationTests)", "test_alter_field_pk_fk (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_target_changes (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_with_to_field_related_name_target_type_change (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_with_to_field_target_changes (migrations.test_operations.OperationTests)", "test_alter_field_reloads_state_on_fk_with_to_field_target_type_change (migrations.test_operations.OperationTests)", "test_alter_field_with_index (migrations.test_operations.OperationTests)", "test_alter_fk (migrations.test_operations.OperationTests)", "test_alter_fk_non_fk (migrations.test_operations.OperationTests)", "test_alter_index_together (migrations.test_operations.OperationTests)", "test_alter_index_together_remove (migrations.test_operations.OperationTests)", "test_alter_model_managers (migrations.test_operations.OperationTests)", "test_alter_model_managers_emptying (migrations.test_operations.OperationTests)", "test_alter_model_options (migrations.test_operations.OperationTests)", "test_alter_model_options_emptying (migrations.test_operations.OperationTests)", "test_alter_model_table (migrations.test_operations.OperationTests)", "test_alter_model_table_m2m (migrations.test_operations.OperationTests)", "test_alter_model_table_none (migrations.test_operations.OperationTests)", "test_alter_model_table_noop (migrations.test_operations.OperationTests)", "test_alter_order_with_respect_to (migrations.test_operations.OperationTests)", "test_alter_unique_together (migrations.test_operations.OperationTests)", "test_alter_unique_together_remove (migrations.test_operations.OperationTests)", "A field may be migrated from AutoField to BigAutoField.", "test_column_name_quoting (migrations.test_operations.OperationTests)", "test_create_model (migrations.test_operations.OperationTests)", "test_create_model_inheritance (migrations.test_operations.OperationTests)", "test_create_model_m2m (migrations.test_operations.OperationTests)", "test_create_model_managers (migrations.test_operations.OperationTests)", "test_create_model_with_constraint (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_base (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_field_name (migrations.test_operations.OperationTests)", "test_create_model_with_duplicate_manager_name (migrations.test_operations.OperationTests)", "test_create_model_with_partial_unique_constraint (migrations.test_operations.OperationTests)", "test_create_model_with_unique_after (migrations.test_operations.OperationTests)", "test_create_proxy_model (migrations.test_operations.OperationTests)", "test_create_unmanaged_model (migrations.test_operations.OperationTests)", "test_delete_model (migrations.test_operations.OperationTests)", "test_delete_mti_model (migrations.test_operations.OperationTests)", "test_delete_proxy_model (migrations.test_operations.OperationTests)", "test_model_with_bigautofield (migrations.test_operations.OperationTests)", "test_remove_constraint (migrations.test_operations.OperationTests)", "test_remove_field (migrations.test_operations.OperationTests)", "test_remove_field_m2m (migrations.test_operations.OperationTests)", "test_remove_field_m2m_with_through (migrations.test_operations.OperationTests)", "test_remove_fk (migrations.test_operations.OperationTests)", "test_remove_index (migrations.test_operations.OperationTests)", "test_remove_index_state_forwards (migrations.test_operations.OperationTests)", "test_remove_partial_unique_constraint (migrations.test_operations.OperationTests)", "test_rename_field (migrations.test_operations.OperationTests)", "test_rename_field_reloads_state_on_fk_target_changes (migrations.test_operations.OperationTests)", "RenameModel renames a many-to-many column after a RenameField.", "test_rename_m2m_target_model (migrations.test_operations.OperationTests)", "test_rename_m2m_through_model (migrations.test_operations.OperationTests)", "test_rename_missing_field (migrations.test_operations.OperationTests)", "test_rename_model (migrations.test_operations.OperationTests)", "test_rename_model_state_forwards (migrations.test_operations.OperationTests)", "test_rename_model_with_m2m (migrations.test_operations.OperationTests)", "test_rename_model_with_self_referential_fk (migrations.test_operations.OperationTests)", "test_rename_model_with_self_referential_m2m (migrations.test_operations.OperationTests)", "test_rename_model_with_superclass_fk (migrations.test_operations.OperationTests)", "test_rename_referenced_field_state_forward (migrations.test_operations.OperationTests)", "test_repoint_field_m2m (migrations.test_operations.OperationTests)", "test_run_python (migrations.test_operations.OperationTests)", "test_run_python_atomic (migrations.test_operations.OperationTests)", "test_run_python_noop (migrations.test_operations.OperationTests)", "test_run_python_related_assignment (migrations.test_operations.OperationTests)", "test_run_sql (migrations.test_operations.OperationTests)", "test_run_sql_noop (migrations.test_operations.OperationTests)", "test_run_sql_params (migrations.test_operations.OperationTests)", "test_run_sql_params_invalid (migrations.test_operations.OperationTests)", "test_separate_database_and_state (migrations.test_operations.OperationTests)", "test_separate_database_and_state2 (migrations.test_operations.OperationTests)", "A field may be migrated from SmallAutoField to AutoField.", "A field may be migrated from SmallAutoField to BigAutoField."]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-13321
35b03788b0607c1f8d2b64e4fa9e1669b0907ea4
diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py --- a/django/contrib/sessions/backends/base.py +++ b/django/contrib/sessions/backends/base.py @@ -121,6 +121,15 @@ def decode(self, session_data): return signing.loads(session_data, salt=self.key_salt, serializer=self.serializer) # RemovedInDjango40Warning: when the deprecation ends, handle here # exceptions similar to what _legacy_decode() does now. + except signing.BadSignature: + try: + # Return an empty session if data is not in the pre-Django 3.1 + # format. + return self._legacy_decode(session_data) + except Exception: + logger = logging.getLogger('django.security.SuspiciousSession') + logger.warning('Session data corrupted') + return {} except Exception: return self._legacy_decode(session_data)
diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py --- a/tests/sessions_tests/tests.py +++ b/tests/sessions_tests/tests.py @@ -333,11 +333,16 @@ def test_default_hashing_algorith_legacy_decode(self): self.assertEqual(self.session._legacy_decode(encoded), data) def test_decode_failure_logged_to_security(self): - bad_encode = base64.b64encode(b'flaskdj:alkdjf').decode('ascii') - with self.assertLogs('django.security.SuspiciousSession', 'WARNING') as cm: - self.assertEqual({}, self.session.decode(bad_encode)) - # The failed decode is logged. - self.assertIn('corrupted', cm.output[0]) + tests = [ + base64.b64encode(b'flaskdj:alkdjf').decode('ascii'), + 'bad:encoded:value', + ] + for encoded in tests: + with self.subTest(encoded=encoded): + with self.assertLogs('django.security.SuspiciousSession', 'WARNING') as cm: + self.assertEqual(self.session.decode(encoded), {}) + # The failed decode is logged. + self.assertIn('Session data corrupted', cm.output[0]) def test_actual_expiry(self): # this doesn't work with JSONSerializer (serializing timedelta)
# Enhanced Problem Statement: Django Session Decoding Crash with Invalid Sessions ## Issue Description After upgrading to Django 3.1, the application crashes when trying to process requests containing invalid or corrupted session data. The issue occurs specifically when browsing to any URL with Chrome browser (but not Firefox), making it impossible to log in or access the application. The root cause is Django's session handling mechanism failing to gracefully handle invalid session data. When an invalid session cookie is encountered, Django first attempts to decode it using the signing mechanism, which fails with a `BadSignature` exception. It then falls back to a legacy decoding method that attempts to base64 decode the data without proper validation, resulting in an unhandled `binascii.Error: Incorrect padding` exception that crashes the request processing pipeline. ## Reproduction Steps 1. Upgrade an existing Django application from a previous version to Django 3.1 2. Leave existing sessions in the database (do not clear them) 3. Using Chrome browser that had a session cookie from before the upgrade, attempt to access any URL in the application 4. Observe the server crash with the following error pattern: ``` 1. Django tries to decode the session with signing.loads() 2. BadSignature exception is raised: "Signature does not match" 3. Falls back to _legacy_decode() method 4. binascii.Error occurs: "Incorrect padding" 5. Exception propagates through the middleware stack, crashing the application ``` The error specifically happens in this sequence: 1. Request processing starts and middleware attempts to authenticate user 2. Session data is accessed via `request.session[SESSION_KEY]` 3. This triggers `_get_session` which calls `load()` from the database backend 4. `load()` calls `decode()` on the session data 5. Primary decoding with `signing.loads()` fails with `BadSignature` 6. Fallback to `_legacy_decode()` attempts base64 decoding 7. Base64 decoding fails with `binascii.Error: Incorrect padding` 8. No exception handling exists for this case, causing the crash ## Expected Behavior When encountering an invalid or corrupted session, Django should gracefully handle the exception by: 1. Catching both `BadSignature` and `binascii.Error` exceptions during session decoding 2. Creating a new, empty session when decoding fails completely 3. Continuing with request processing using the fresh session 4. Allowing the user to log in or access the site normally, even with a previously corrupted session ## Exploration Hints ### Files to Examine: - **django/contrib/sessions/backends/base.py** - Contains the core session decoding logic including the `decode()` and `_legacy_decode()` methods that are failing. This file implements the basic session handling framework that all session backends inherit from. - **django/contrib/sessions/backends/db.py** - Implements database-backed sessions with the `load()` method that retrieves session data from the database and attempts to decode it without proper error handling. - **django/core/signing.py** - Contains the cryptographic signing code used for session security; the `loads()` and `TimestampSigner.unsign()` methods are involved in the failure path when trying to validate session signatures. ### Key Classes/Functions: - **SessionBase.decode()** - Responsible for decoding session data; contains a two-step approach that first tries the signing module and falls back to legacy decoding on `BadSignature` error. This method needs improved error handling. - **SessionBase._legacy_decode()** - Attempts base64 decoding of session data without validation, causing the unhandled exception when the data is malformed. - **SessionStore.load()** (in db.py) - Retrieves session from database and calls `decode()` without proper error handling for decode failures. - **signing.loads()** - Validates and decodes signed data; raises `BadSignature` when a session's signature is invalid. ### Areas of Interest: - Exception handling around session decoding is currently insufficient, particularly for base64 decoding errors - Different behavior between browsers suggests possible differences in cookie handling (Chrome vs Firefox) - The upgrade path to Django 3.1 appears to have changed session format or validation without proper migration of existing sessions - Session data flow: browser cookie → middleware → session backend → decode method → application ## Fix Hints ### High Confidence Locations: - **django/contrib/sessions/backends/base.py** - The `_legacy_decode()` method needs to catch `binascii.Error` exceptions and handle them gracefully. - **django/contrib/sessions/backends/base.py** - The `decode()` method should have improved error handling to create a new session when decoding completely fails. ### Implementation Hints: 1. Modify `_legacy_decode()` to wrap the base64 decoding in a try/except block: ```python def _legacy_decode(self, session_data): try: encoded_data = base64.b64decode(session_data.encode('ascii')) # continue with normal decoding except (binascii.Error, UnicodeEncodeError): return {} # Return an empty session on decode failure ``` 2. Enhance the `load()` method in db.py to gracefully handle decode errors: ```python def load(self): try: return self.decode(s.session_data) if s else {} except Exception: # Log the exception but don't crash return {} ``` ### Alternative Hypotheses: 1. **Browser-specific cookie handling** - Chrome might be handling cookies differently than Firefox, potentially truncating or modifying session cookies in a way that causes the base64 padding error. 2. **Proxy server interference** - The nginx proxy mentioned in the report might be modifying or corrupting cookies during request processing. 3. **Session migration issue** - The upgrade to Django 3.1 may have changed session format requirements without properly migrating existing sessions. 4. **Database corruption** - Session data in the database might be corrupted, particularly if the database wasn't properly maintained during the upgrade process. 5. **Middleware interaction** - The error might be related to the interaction between session middleware and other middleware components (like django_otp visible in the traceback), particularly in how they handle authentication state when sessions are invalid.
I tried to run clearsessions, but that didn't help. The only workaround was to delete all rows in the django_session table. Thanks for this report, however I cannot reproduce this issue. Can you provide a sample project? Support for user sessions created by older versions of Django remains until Django 4.0. See similar tickets #31864, #31592, and #31274, this can be a duplicate of one of them. Thanks for the response. It does look similar to the other issues you posted. I don't have a reproducible instance at present. The only way I can think to reproduce would be to start up a 3.0 site, login, wait for the session to expire, then upgrade to 3.1. These are the steps that would have happened on the environment where I encountered the issue. Thanks I was able to reproduce this issue with an invalid session data. Regression in d4fff711d4c97356bd6ba1273d2a5e349326eb5f.
2020-08-18T10:43:52Z
3.2
["test_clear (sessions_tests.tests.CookieSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.CookieSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.CookieSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.CookieSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.CookieSessionTests)", "test_cycle (sessions_tests.tests.CookieSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.CookieSessionTests)", "test_decode (sessions_tests.tests.CookieSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.CookieSessionTests)", "test_decode_legacy (sessions_tests.tests.CookieSessionTests)", "test_default_expiry (sessions_tests.tests.CookieSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.CookieSessionTests)", "test_delete (sessions_tests.tests.CookieSessionTests)", "test_flush (sessions_tests.tests.CookieSessionTests)", "test_get_empty (sessions_tests.tests.CookieSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.CookieSessionTests)", "test_has_key (sessions_tests.tests.CookieSessionTests)", "test_invalid_key (sessions_tests.tests.CookieSessionTests)", "test_items (sessions_tests.tests.CookieSessionTests)", "test_keys (sessions_tests.tests.CookieSessionTests)", "test_new_session (sessions_tests.tests.CookieSessionTests)", "test_pop (sessions_tests.tests.CookieSessionTests)", "test_pop_default (sessions_tests.tests.CookieSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.CookieSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.CookieSessionTests)", "test_save (sessions_tests.tests.CookieSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.CookieSessionTests)", "Falsey values (Such as an empty string) are rejected.", "test_session_key_is_read_only (sessions_tests.tests.CookieSessionTests)", "Strings shorter than 8 characters are rejected.", "Strings of length 8 and up are accepted and stored.", "test_setdefault (sessions_tests.tests.CookieSessionTests)", "test_store (sessions_tests.tests.CookieSessionTests)", "test_unpickling_exception (sessions_tests.tests.CookieSessionTests)", "test_update (sessions_tests.tests.CookieSessionTests)", "test_values (sessions_tests.tests.CookieSessionTests)", "test_actual_expiry (sessions_tests.tests.CacheSessionTests)", "test_clear (sessions_tests.tests.CacheSessionTests)", "test_create_and_save (sessions_tests.tests.CacheSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.CacheSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.CacheSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.CacheSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.CacheSessionTests)", "test_cycle (sessions_tests.tests.CacheSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.CacheSessionTests)", "test_decode (sessions_tests.tests.CacheSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.CacheSessionTests)", "test_decode_legacy (sessions_tests.tests.CacheSessionTests)", "test_default_cache (sessions_tests.tests.CacheSessionTests)", "test_default_expiry (sessions_tests.tests.CacheSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.CacheSessionTests)", "test_delete (sessions_tests.tests.CacheSessionTests)", "test_flush (sessions_tests.tests.CacheSessionTests)", "test_get_empty (sessions_tests.tests.CacheSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.CacheSessionTests)", "test_has_key (sessions_tests.tests.CacheSessionTests)", "test_invalid_key (sessions_tests.tests.CacheSessionTests)", "test_items (sessions_tests.tests.CacheSessionTests)", "test_keys (sessions_tests.tests.CacheSessionTests)", "test_load_overlong_key (sessions_tests.tests.CacheSessionTests)", "test_new_session (sessions_tests.tests.CacheSessionTests)", "test_non_default_cache (sessions_tests.tests.CacheSessionTests)", "test_pop (sessions_tests.tests.CacheSessionTests)", "test_pop_default (sessions_tests.tests.CacheSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.CacheSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.CacheSessionTests)", "test_save (sessions_tests.tests.CacheSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.CacheSessionTests)", "test_session_key_is_read_only (sessions_tests.tests.CacheSessionTests)", "test_session_load_does_not_create_record (sessions_tests.tests.CacheSessionTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.CacheSessionTests)", "test_setdefault (sessions_tests.tests.CacheSessionTests)", "test_store (sessions_tests.tests.CacheSessionTests)", "test_update (sessions_tests.tests.CacheSessionTests)", "test_values (sessions_tests.tests.CacheSessionTests)", "test_empty_session_saved (sessions_tests.tests.SessionMiddlewareTests)", "test_flush_empty_without_session_cookie_doesnt_set_cookie (sessions_tests.tests.SessionMiddlewareTests)", "test_httponly_session_cookie (sessions_tests.tests.SessionMiddlewareTests)", "test_no_httponly_session_cookie (sessions_tests.tests.SessionMiddlewareTests)", "test_samesite_session_cookie (sessions_tests.tests.SessionMiddlewareTests)", "test_secure_session_cookie (sessions_tests.tests.SessionMiddlewareTests)", "test_session_delete_on_end (sessions_tests.tests.SessionMiddlewareTests)", "test_session_delete_on_end_with_custom_domain_and_path (sessions_tests.tests.SessionMiddlewareTests)", "test_session_save_on_500 (sessions_tests.tests.SessionMiddlewareTests)", "test_session_update_error_redirect (sessions_tests.tests.SessionMiddlewareTests)", "test_actual_expiry (sessions_tests.tests.FileSessionPathLibTests)", "test_clear (sessions_tests.tests.FileSessionPathLibTests)", "test_clearsessions_command (sessions_tests.tests.FileSessionPathLibTests)", "test_configuration_check (sessions_tests.tests.FileSessionPathLibTests)", "test_custom_expiry_datetime (sessions_tests.tests.FileSessionPathLibTests)", "test_custom_expiry_reset (sessions_tests.tests.FileSessionPathLibTests)", "test_custom_expiry_seconds (sessions_tests.tests.FileSessionPathLibTests)", "test_custom_expiry_timedelta (sessions_tests.tests.FileSessionPathLibTests)", "test_cycle (sessions_tests.tests.FileSessionPathLibTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.FileSessionPathLibTests)", "test_decode (sessions_tests.tests.FileSessionPathLibTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.FileSessionPathLibTests)", "test_decode_legacy (sessions_tests.tests.FileSessionPathLibTests)", "test_default_expiry (sessions_tests.tests.FileSessionPathLibTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.FileSessionPathLibTests)", "test_delete (sessions_tests.tests.FileSessionPathLibTests)", "test_flush (sessions_tests.tests.FileSessionPathLibTests)", "test_get_empty (sessions_tests.tests.FileSessionPathLibTests)", "test_get_expire_at_browser_close (sessions_tests.tests.FileSessionPathLibTests)", "test_has_key (sessions_tests.tests.FileSessionPathLibTests)", "test_invalid_key (sessions_tests.tests.FileSessionPathLibTests)", "test_invalid_key_backslash (sessions_tests.tests.FileSessionPathLibTests)", "test_invalid_key_forwardslash (sessions_tests.tests.FileSessionPathLibTests)", "test_items (sessions_tests.tests.FileSessionPathLibTests)", "test_keys (sessions_tests.tests.FileSessionPathLibTests)", "test_new_session (sessions_tests.tests.FileSessionPathLibTests)", "test_pop (sessions_tests.tests.FileSessionPathLibTests)", "test_pop_default (sessions_tests.tests.FileSessionPathLibTests)", "test_pop_default_named_argument (sessions_tests.tests.FileSessionPathLibTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.FileSessionPathLibTests)", "test_save (sessions_tests.tests.FileSessionPathLibTests)", "test_save_doesnt_clear_data (sessions_tests.tests.FileSessionPathLibTests)", "test_session_key_is_read_only (sessions_tests.tests.FileSessionPathLibTests)", "test_session_load_does_not_create_record (sessions_tests.tests.FileSessionPathLibTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.FileSessionPathLibTests)", "test_setdefault (sessions_tests.tests.FileSessionPathLibTests)", "test_store (sessions_tests.tests.FileSessionPathLibTests)", "test_update (sessions_tests.tests.FileSessionPathLibTests)", "test_values (sessions_tests.tests.FileSessionPathLibTests)", "test_actual_expiry (sessions_tests.tests.FileSessionTests)", "test_clear (sessions_tests.tests.FileSessionTests)", "test_clearsessions_command (sessions_tests.tests.FileSessionTests)", "test_configuration_check (sessions_tests.tests.FileSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.FileSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.FileSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.FileSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.FileSessionTests)", "test_cycle (sessions_tests.tests.FileSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.FileSessionTests)", "test_decode (sessions_tests.tests.FileSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.FileSessionTests)", "test_decode_legacy (sessions_tests.tests.FileSessionTests)", "test_default_expiry (sessions_tests.tests.FileSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.FileSessionTests)", "test_delete (sessions_tests.tests.FileSessionTests)", "test_flush (sessions_tests.tests.FileSessionTests)", "test_get_empty (sessions_tests.tests.FileSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.FileSessionTests)", "test_has_key (sessions_tests.tests.FileSessionTests)", "test_invalid_key (sessions_tests.tests.FileSessionTests)", "test_invalid_key_backslash (sessions_tests.tests.FileSessionTests)", "test_invalid_key_forwardslash (sessions_tests.tests.FileSessionTests)", "test_items (sessions_tests.tests.FileSessionTests)", "test_keys (sessions_tests.tests.FileSessionTests)", "test_new_session (sessions_tests.tests.FileSessionTests)", "test_pop (sessions_tests.tests.FileSessionTests)", "test_pop_default (sessions_tests.tests.FileSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.FileSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.FileSessionTests)", "test_save (sessions_tests.tests.FileSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.FileSessionTests)", "test_session_key_is_read_only (sessions_tests.tests.FileSessionTests)", "test_session_load_does_not_create_record (sessions_tests.tests.FileSessionTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.FileSessionTests)", "test_setdefault (sessions_tests.tests.FileSessionTests)", "test_store (sessions_tests.tests.FileSessionTests)", "test_update (sessions_tests.tests.FileSessionTests)", "test_values (sessions_tests.tests.FileSessionTests)", "test_actual_expiry (sessions_tests.tests.DatabaseSessionTests)", "test_clear (sessions_tests.tests.DatabaseSessionTests)", "test_clearsessions_command (sessions_tests.tests.DatabaseSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.DatabaseSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.DatabaseSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.DatabaseSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.DatabaseSessionTests)", "test_cycle (sessions_tests.tests.DatabaseSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.DatabaseSessionTests)", "test_decode (sessions_tests.tests.DatabaseSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.DatabaseSessionTests)", "test_decode_legacy (sessions_tests.tests.DatabaseSessionTests)", "test_default_expiry (sessions_tests.tests.DatabaseSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.DatabaseSessionTests)", "test_delete (sessions_tests.tests.DatabaseSessionTests)", "test_flush (sessions_tests.tests.DatabaseSessionTests)", "test_get_empty (sessions_tests.tests.DatabaseSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.DatabaseSessionTests)", "test_has_key (sessions_tests.tests.DatabaseSessionTests)", "test_invalid_key (sessions_tests.tests.DatabaseSessionTests)", "test_items (sessions_tests.tests.DatabaseSessionTests)", "test_keys (sessions_tests.tests.DatabaseSessionTests)", "test_new_session (sessions_tests.tests.DatabaseSessionTests)", "test_pop (sessions_tests.tests.DatabaseSessionTests)", "test_pop_default (sessions_tests.tests.DatabaseSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.DatabaseSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.DatabaseSessionTests)", "test_save (sessions_tests.tests.DatabaseSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.DatabaseSessionTests)", "test_session_get_decoded (sessions_tests.tests.DatabaseSessionTests)", "test_session_key_is_read_only (sessions_tests.tests.DatabaseSessionTests)", "test_session_load_does_not_create_record (sessions_tests.tests.DatabaseSessionTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.DatabaseSessionTests)", "Session repr should be the session key.", "test_sessionmanager_save (sessions_tests.tests.DatabaseSessionTests)", "test_setdefault (sessions_tests.tests.DatabaseSessionTests)", "test_store (sessions_tests.tests.DatabaseSessionTests)", "test_update (sessions_tests.tests.DatabaseSessionTests)", "test_values (sessions_tests.tests.DatabaseSessionTests)", "test_actual_expiry (sessions_tests.tests.CustomDatabaseSessionTests)", "test_clear (sessions_tests.tests.CustomDatabaseSessionTests)", "test_clearsessions_command (sessions_tests.tests.CustomDatabaseSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.CustomDatabaseSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.CustomDatabaseSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.CustomDatabaseSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.CustomDatabaseSessionTests)", "test_cycle (sessions_tests.tests.CustomDatabaseSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.CustomDatabaseSessionTests)", "test_decode (sessions_tests.tests.CustomDatabaseSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.CustomDatabaseSessionTests)", "test_decode_legacy (sessions_tests.tests.CustomDatabaseSessionTests)", "test_default_expiry (sessions_tests.tests.CustomDatabaseSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.CustomDatabaseSessionTests)", "test_delete (sessions_tests.tests.CustomDatabaseSessionTests)", "test_extra_session_field (sessions_tests.tests.CustomDatabaseSessionTests)", "test_flush (sessions_tests.tests.CustomDatabaseSessionTests)", "test_get_empty (sessions_tests.tests.CustomDatabaseSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.CustomDatabaseSessionTests)", "test_has_key (sessions_tests.tests.CustomDatabaseSessionTests)", "test_invalid_key (sessions_tests.tests.CustomDatabaseSessionTests)", "test_items (sessions_tests.tests.CustomDatabaseSessionTests)", "test_keys (sessions_tests.tests.CustomDatabaseSessionTests)", "test_new_session (sessions_tests.tests.CustomDatabaseSessionTests)", "test_pop (sessions_tests.tests.CustomDatabaseSessionTests)", "test_pop_default (sessions_tests.tests.CustomDatabaseSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.CustomDatabaseSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.CustomDatabaseSessionTests)", "test_save (sessions_tests.tests.CustomDatabaseSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.CustomDatabaseSessionTests)", "test_session_get_decoded (sessions_tests.tests.CustomDatabaseSessionTests)", "test_session_key_is_read_only (sessions_tests.tests.CustomDatabaseSessionTests)", "test_session_load_does_not_create_record (sessions_tests.tests.CustomDatabaseSessionTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.CustomDatabaseSessionTests)", "test_sessionmanager_save (sessions_tests.tests.CustomDatabaseSessionTests)", "test_setdefault (sessions_tests.tests.CustomDatabaseSessionTests)", "test_store (sessions_tests.tests.CustomDatabaseSessionTests)", "test_update (sessions_tests.tests.CustomDatabaseSessionTests)", "test_values (sessions_tests.tests.CustomDatabaseSessionTests)", "test_actual_expiry (sessions_tests.tests.CacheDBSessionTests)", "test_clear (sessions_tests.tests.CacheDBSessionTests)", "test_custom_expiry_datetime (sessions_tests.tests.CacheDBSessionTests)", "test_custom_expiry_reset (sessions_tests.tests.CacheDBSessionTests)", "test_custom_expiry_seconds (sessions_tests.tests.CacheDBSessionTests)", "test_custom_expiry_timedelta (sessions_tests.tests.CacheDBSessionTests)", "test_cycle (sessions_tests.tests.CacheDBSessionTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.CacheDBSessionTests)", "test_decode (sessions_tests.tests.CacheDBSessionTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.CacheDBSessionTests)", "test_decode_legacy (sessions_tests.tests.CacheDBSessionTests)", "test_default_expiry (sessions_tests.tests.CacheDBSessionTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.CacheDBSessionTests)", "test_delete (sessions_tests.tests.CacheDBSessionTests)", "test_exists_searches_cache_first (sessions_tests.tests.CacheDBSessionTests)", "test_flush (sessions_tests.tests.CacheDBSessionTests)", "test_get_empty (sessions_tests.tests.CacheDBSessionTests)", "test_get_expire_at_browser_close (sessions_tests.tests.CacheDBSessionTests)", "test_has_key (sessions_tests.tests.CacheDBSessionTests)", "test_invalid_key (sessions_tests.tests.CacheDBSessionTests)", "test_items (sessions_tests.tests.CacheDBSessionTests)", "test_keys (sessions_tests.tests.CacheDBSessionTests)", "test_load_overlong_key (sessions_tests.tests.CacheDBSessionTests)", "test_new_session (sessions_tests.tests.CacheDBSessionTests)", "test_non_default_cache (sessions_tests.tests.CacheDBSessionTests)", "test_pop (sessions_tests.tests.CacheDBSessionTests)", "test_pop_default (sessions_tests.tests.CacheDBSessionTests)", "test_pop_default_named_argument (sessions_tests.tests.CacheDBSessionTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.CacheDBSessionTests)", "test_save (sessions_tests.tests.CacheDBSessionTests)", "test_save_doesnt_clear_data (sessions_tests.tests.CacheDBSessionTests)", "test_session_key_is_read_only (sessions_tests.tests.CacheDBSessionTests)", "test_session_load_does_not_create_record (sessions_tests.tests.CacheDBSessionTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.CacheDBSessionTests)", "test_setdefault (sessions_tests.tests.CacheDBSessionTests)", "test_store (sessions_tests.tests.CacheDBSessionTests)", "test_update (sessions_tests.tests.CacheDBSessionTests)", "test_values (sessions_tests.tests.CacheDBSessionTests)", "test_actual_expiry (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_clear (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_custom_expiry_datetime (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_custom_expiry_reset (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_custom_expiry_seconds (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_custom_expiry_timedelta (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_cycle (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_decode (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_decode_legacy (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_default_expiry (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_delete (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_exists_searches_cache_first (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_flush (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_get_empty (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_get_expire_at_browser_close (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_has_key (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_invalid_key (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_items (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_keys (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_load_overlong_key (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_new_session (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_non_default_cache (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_pop (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_pop_default (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_pop_default_named_argument (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_save (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_save_doesnt_clear_data (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_session_key_is_read_only (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_session_load_does_not_create_record (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_setdefault (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_store (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_update (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_values (sessions_tests.tests.CacheDBSessionWithTimeZoneTests)", "test_actual_expiry (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_clear (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_clearsessions_command (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_custom_expiry_datetime (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_custom_expiry_reset (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_custom_expiry_seconds (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_custom_expiry_timedelta (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_cycle (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_cycle_with_no_session_cache (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_decode (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_decode_failure_logged_to_security (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_decode_legacy (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_default_expiry (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_default_hashing_algorith_legacy_decode (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_delete (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_flush (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_get_empty (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_get_expire_at_browser_close (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_has_key (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_invalid_key (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_items (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_keys (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_new_session (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_pop (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_pop_default (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_pop_default_named_argument (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_pop_no_default_keyerror_raised (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_save (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_save_doesnt_clear_data (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_session_get_decoded (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_session_key_is_read_only (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_session_load_does_not_create_record (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_session_save_does_not_resurrect_session_logged_out_in_other_context (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_sessionmanager_save (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_setdefault (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_store (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_update (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)", "test_values (sessions_tests.tests.DatabaseSessionWithTimeZoneTests)"]
[]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django/django
django__django-12908
49ae7ce50a874f8a04cd910882fb9571ff3a0d7a
diff --git a/django/db/models/query.py b/django/db/models/query.py --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1138,6 +1138,7 @@ def distinct(self, *field_names): """ Return a new QuerySet instance that will select only distinct results. """ + self._not_support_combined_queries('distinct') assert not self.query.is_sliced, \ "Cannot create distinct fields once a slice has been taken." obj = self._chain()
diff --git a/tests/queries/test_qs_combinators.py b/tests/queries/test_qs_combinators.py --- a/tests/queries/test_qs_combinators.py +++ b/tests/queries/test_qs_combinators.py @@ -272,6 +272,7 @@ def test_unsupported_operations_on_combined_qs(self): 'annotate', 'defer', 'delete', + 'distinct', 'exclude', 'extra', 'filter',
# Enhanced Problem Statement: DISTINCT ON Not Working with UNION Queryset ## Issue Description When applying `.distinct()` with field arguments (e.g., `.distinct('name')`) on a queryset that is the result of a `.union()` operation on annotated querysets, the distinct operation is not properly applied to the combined results. This occurs because the SQL compiler does not correctly wrap the UNION query in a subquery before applying the DISTINCT ON clause. Instead of generating SQL that applies DISTINCT ON to the outer query wrapping the union, the operation appears to be ignored or improperly applied to the individual parts of the union. This issue specifically affects PostgreSQL's DISTINCT ON functionality. ## Reproduction Steps ```python def setUp(self) -> None: user = self.get_or_create_admin_user() Sample.h.create(user, name="Sam1") Sample.h.create(user, name="Sam2 acid") Sample.h.create(user, name="Sam3") Sample.h.create(user, name="Sam4 acid") Sample.h.create(user, name="Dub") Sample.h.create(user, name="Dub") Sample.h.create(user, name="Dub") self.user = user def test_union_annotated_diff_distinct(self): qs = Sample.objects.filter(user=self.user) qs1 = qs.filter(name='Dub').annotate(rank=Value(0, IntegerField())) qs2 = qs.filter(name='Sam1').annotate(rank=Value(1, IntegerField())) qs = qs1.union(qs2) qs = qs.order_by('name').distinct('name') # THIS DISTINCT DOESN'T WORK self.assertEqual(qs.count(), 2) # This fails because distinct is not effective ``` Internally, what happens is: 1. Two querysets are created with annotations 2. The querysets are combined with `union()` 3. The `distinct('name')` operation is applied to the combined queryset 4. When the SQL is compiled, the DISTINCT ON clause is not properly applied to the outer query wrapping the union The expected SQL should be: ```sql SELECT DISTINCT ON (siebox_sample.name) * FROM (SELECT ... UNION SELECT ...) AS siebox_sample ``` But the generated SQL doesn't correctly wrap the DISTINCT ON around the union result, causing the distinct operation to be ineffective. ## Expected Behavior When calling `.distinct('name')` on a unioned queryset, Django should generate SQL that applies the DISTINCT ON clause to the outer query that wraps the union operation. The final SQL should have the form: ```sql SELECT DISTINCT ON (table_alias.name) * FROM (SELECT ... UNION SELECT ...) AS table_alias ``` This would ensure that the distinct operation correctly filters rows with duplicate name values from the combined result set, resulting in exactly 2 records in the example test case. ## Exploration Hints ### Files to Examine: - **django/db/models/query.py** - Contains the `QuerySet` class with the `union()` and `distinct()` methods. The issue involves how these methods interact and how the resulting query structure is built. - **django/db/models/sql/compiler.py** - Contains the SQL compilation logic that transforms Django ORM queries into actual SQL statements. The bug is likely in how the compiler handles distinct operations on union querysets. - **django/db/backends/postgresql/operations.py** - Contains PostgreSQL-specific operations, including how DISTINCT ON queries are handled. The issue is specific to PostgreSQL's DISTINCT ON feature. ### Key Classes/Functions: - **QuerySet._combinator_query()** - Handles the logic for combining querysets using SQL combinators like UNION. Needs examination to see how it preserves the ability to apply post-union operations. - **QuerySet.distinct()** - Adds distinct fields to the query, but might not be properly interacting with combined queries. - **SQLCompiler.get_distinct()** - Responsible for generating the DISTINCT part of the SQL query. May not handle union querysets correctly. - **SQLCompiler.get_combinator_sql()** - Handles SQL generation for combinator operations like UNION. May not preserve distinct operations. - **DatabaseOperations.distinct_sql** (PostgreSQL backend) - Generates PostgreSQL-specific DISTINCT ON syntax. May need adjustments for union queries. ### Areas of Interest: - How query combination operations (like union) create composite query structures - How distinct operations are propagated through the query compilation process - The interaction between annotation, union, and distinct operations - How PostgreSQL's DISTINCT ON syntax is handled differently from regular DISTINCT - The ordering of operations during SQL compilation when both UNION and DISTINCT are present ## Fix Hints ### High Confidence Locations: - **SQLCompiler.get_combinator_sql()** method - This method generates SQL for UNION and other combinators, but likely doesn't properly handle subsequent operations like distinct. It needs to be modified to ensure that operations like DISTINCT ON are applied to the outer query wrapping the union. ### Implementation Hints: - The fix likely involves restructuring how combined queries are wrapped during SQL compilation - When a distinct operation is detected on a combined query, the SQL compiler needs to ensure it wraps the union result in a subquery before applying the DISTINCT ON clause - May require changes to how table aliases are managed when applying distinct to a union query - Consider refactoring the query compilation process to better separate the stages of union query generation and application of operations like distinct ### Alternative Hypotheses: - The issue might be in the query's `combine()` method rather than in the SQL compiler, as it may not properly preserve distinct flags when combining queries - The problem could be specific to how field references work in the context of a union query with annotations, causing the distinct operation to target the wrong fields - It's possible that there's a deeper architectural issue with how Django handles complex query combinations, where certain operation orderings aren't fully supported The most likely solution involves modifying the SQL compiler to ensure that DISTINCT ON operations are applied as an outer wrapper around UNION queries rather than trying to incorporate them into the individual queries being united.
distinct() is not supported but doesn't raise an error yet. As ​​per the documentation, "only LIMIT, OFFSET, COUNT(*), ORDER BY, and specifying columns (i.e. slicing, count(), order_by(), and values()/values_list()) are allowed on the resulting QuerySet.". Follow up to #27995.
2020-05-13T11:36:48Z
3.2
["test_unsupported_operations_on_combined_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_unsupported_ordering_slicing_raises_db_error (queries.test_qs_combinators.QuerySetSetOperationTests)"]
["test_combining_multiple_models (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_difference (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_intersection (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_union (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_union_empty_result (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_difference_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_difference_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_intersection_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_intersection_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_limits (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_order_by_same_type (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_order_raises_on_non_selected_column (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_ordering (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_ordering_by_f_expression (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_qs_with_subcompound_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_simple_difference (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_simple_intersection (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_simple_union (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_distinct (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_extra_and_values_list (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_two_annotated_values_list (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_values_list_and_order (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_values_list_on_annotated_and_unannotated (queries.test_qs_combinators.QuerySetSetOperationTests)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django/django
django__django-15061
2c01ebb4be5d53cbf6450f356c10e436025d6d07
diff --git a/django/forms/widgets.py b/django/forms/widgets.py --- a/django/forms/widgets.py +++ b/django/forms/widgets.py @@ -849,9 +849,7 @@ def get_context(self, name, value, attrs): return context def id_for_label(self, id_): - if id_: - id_ += '_0' - return id_ + return '' def value_from_datadict(self, data, files, name): return [
diff --git a/tests/forms_tests/field_tests/test_multivaluefield.py b/tests/forms_tests/field_tests/test_multivaluefield.py --- a/tests/forms_tests/field_tests/test_multivaluefield.py +++ b/tests/forms_tests/field_tests/test_multivaluefield.py @@ -141,7 +141,7 @@ def test_form_as_table(self): self.assertHTMLEqual( form.as_table(), """ - <tr><th><label for="id_field1_0">Field1:</label></th> + <tr><th><label>Field1:</label></th> <td><input type="text" name="field1_0" id="id_field1_0" required> <select multiple name="field1_1" id="id_field1_1" required> <option value="J">John</option> @@ -164,7 +164,7 @@ def test_form_as_table_data(self): self.assertHTMLEqual( form.as_table(), """ - <tr><th><label for="id_field1_0">Field1:</label></th> + <tr><th><label>Field1:</label></th> <td><input type="text" name="field1_0" value="some text" id="id_field1_0" required> <select multiple name="field1_1" id="id_field1_1" required> <option value="J" selected>John</option> diff --git a/tests/forms_tests/field_tests/test_splitdatetimefield.py b/tests/forms_tests/field_tests/test_splitdatetimefield.py --- a/tests/forms_tests/field_tests/test_splitdatetimefield.py +++ b/tests/forms_tests/field_tests/test_splitdatetimefield.py @@ -1,7 +1,7 @@ import datetime from django.core.exceptions import ValidationError -from django.forms import SplitDateTimeField +from django.forms import Form, SplitDateTimeField from django.forms.widgets import SplitDateTimeWidget from django.test import SimpleTestCase @@ -60,3 +60,16 @@ def test_splitdatetimefield_changed(self): self.assertTrue(f.has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['2008-05-06', '12:40:00'])) self.assertFalse(f.has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06/05/2008', '12:40'])) self.assertTrue(f.has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06/05/2008', '12:41'])) + + def test_form_as_table(self): + class TestForm(Form): + datetime = SplitDateTimeField() + + f = TestForm() + self.assertHTMLEqual( + f.as_table(), + '<tr><th><label>Datetime:</label></th><td>' + '<input type="text" name="datetime_0" required id="id_datetime_0">' + '<input type="text" name="datetime_1" required id="id_datetime_1">' + '</td></tr>', + ) diff --git a/tests/postgres_tests/test_ranges.py b/tests/postgres_tests/test_ranges.py --- a/tests/postgres_tests/test_ranges.py +++ b/tests/postgres_tests/test_ranges.py @@ -665,7 +665,7 @@ class SplitForm(forms.Form): self.assertHTMLEqual(str(form), ''' <tr> <th> - <label for="id_field_0">Field:</label> + <label>Field:</label> </th> <td> <input id="id_field_0_0" name="field_0_0" type="text"> @@ -700,7 +700,7 @@ class DateTimeRangeForm(forms.Form): form.as_table(), """ <tr><th> - <label for="id_datetime_field_0">Datetime field:</label> + <label>Datetime field:</label> </th><td> <input type="text" name="datetime_field_0" id="id_datetime_field_0"> <input type="text" name="datetime_field_1" id="id_datetime_field_1"> @@ -717,7 +717,7 @@ class DateTimeRangeForm(forms.Form): form.as_table(), """ <tr><th> - <label for="id_datetime_field_0">Datetime field:</label> + <label>Datetime field:</label> </th><td> <input type="text" name="datetime_field_0" value="2010-01-01 11:13:00" id="id_datetime_field_0"> @@ -754,7 +754,7 @@ class RangeForm(forms.Form): self.assertHTMLEqual(str(RangeForm()), ''' <tr> - <th><label for="id_ints_0">Ints:</label></th> + <th><label>Ints:</label></th> <td> <input id="id_ints_0" name="ints_0" type="number"> <input id="id_ints_1" name="ints_1" type="number">
Remove "for = ..." from MultiWidget's <label>. Description The instance from Raw MultiWidget class generate id_for_label like f'{id_}0' It has not sense. For example ChoiceWidget has self.add_id_index and I can decide it myself, how I will see label_id - with or without index. I think, it is better to remove completely id_for_label method from MultiWidget Class.
I agree that we should remove for from MultiWidget's <label> but not because "It has not sense" but to improve accessibility when using a screen reader, see also #32338. It should be enough to return an empty string: def id_for_label(self, id_): return '' ​PR
2021-11-04T17:15:53Z
4.1
["test_form_as_table (forms_tests.field_tests.test_multivaluefield.MultiValueFieldTest)", "test_form_as_table_data (forms_tests.field_tests.test_multivaluefield.MultiValueFieldTest)", "test_form_as_table (forms_tests.field_tests.test_splitdatetimefield.SplitDateTimeFieldTest)"]
["test_bad_choice (forms_tests.field_tests.test_multivaluefield.MultiValueFieldTest)", "test_clean (forms_tests.field_tests.test_multivaluefield.MultiValueFieldTest)", "test_clean_disabled_multivalue (forms_tests.field_tests.test_multivaluefield.MultiValueFieldTest)", "test_disabled_has_changed (forms_tests.field_tests.test_multivaluefield.MultiValueFieldTest)", "test_form_cleaned_data (forms_tests.field_tests.test_multivaluefield.MultiValueFieldTest)", "Test when the first widget's data has changed.", "Test when the last widget's data has changed. This ensures that it is", "test_has_changed_no_initial (forms_tests.field_tests.test_multivaluefield.MultiValueFieldTest)", "test_has_changed_same (forms_tests.field_tests.test_multivaluefield.MultiValueFieldTest)", "If insufficient data is provided, None is substituted.", "test_render_required_attributes (forms_tests.field_tests.test_multivaluefield.MultiValueFieldTest)", "test_splitdatetimefield_1 (forms_tests.field_tests.test_splitdatetimefield.SplitDateTimeFieldTest)", "test_splitdatetimefield_2 (forms_tests.field_tests.test_splitdatetimefield.SplitDateTimeFieldTest)", "test_splitdatetimefield_changed (forms_tests.field_tests.test_splitdatetimefield.SplitDateTimeFieldTest)"]
647480166bfe7532e8c471fef0146e3a17e6c0c9
django/django
django__django-13158
7af8f4127397279d19ef7c7899e93018274e2f9b
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -305,6 +305,7 @@ def clone(self): obj.annotation_select_mask = None else: obj.annotation_select_mask = self.annotation_select_mask.copy() + obj.combined_queries = tuple(query.clone() for query in self.combined_queries) # _annotation_select_cache cannot be copied, as doing so breaks the # (necessary) state in which both annotations and # _annotation_select_cache point to the same underlying objects. @@ -1777,6 +1778,8 @@ def split_exclude(self, filter_expr, can_reuse, names_with_path): def set_empty(self): self.where.add(NothingNode(), AND) + for query in self.combined_queries: + query.set_empty() def is_empty(self): return any(isinstance(c, NothingNode) for c in self.where.children)
diff --git a/tests/queries/test_qs_combinators.py b/tests/queries/test_qs_combinators.py --- a/tests/queries/test_qs_combinators.py +++ b/tests/queries/test_qs_combinators.py @@ -51,6 +51,13 @@ def test_union_distinct(self): self.assertEqual(len(list(qs1.union(qs2, all=True))), 20) self.assertEqual(len(list(qs1.union(qs2))), 10) + def test_union_none(self): + qs1 = Number.objects.filter(num__lte=1) + qs2 = Number.objects.filter(num__gte=8) + qs3 = qs1.union(qs2) + self.assertSequenceEqual(qs3.none(), []) + self.assertNumbersEqual(qs3, [0, 1, 8, 9], ordered=False) + @skipUnlessDBFeature('supports_select_intersection') def test_intersection_with_empty_qs(self): qs1 = Number.objects.all()
# QuerySet.none() on Combined Queries Returns All Results ## Issue Description When using Django's `ModelMultipleChoiceField` with a queryset created using the `union()` method, and then submitting a form with no selections, all objects matching the queryset are incorrectly added to the many-to-many relationship. This behavior differs from using the OR operator (`|`), which correctly adds no objects when no selections are made. The issue appears to stem from an inconsistency in how Django's ORM handles the `none()` method on combined querysets created with SQL combinators (like `union()`) versus Python-level combinations (via `|`). ## Reproduction Steps ```python class Publication(models.Model): pass class Article(models.Model): publications = models.ManyToManyField(to=Publication, blank=True, null=True) class ArticleForm(forms.ModelForm): # This works correctly - no selections means no objects added publications = forms.ModelMultipleChoiceField( Publication.objects.filter(id__lt=2) | Publication.objects.filter(id__gt=5), required=False, ) # This causes the bug - no selections means ALL objects are added publications = forms.ModelMultipleChoiceField( Publication.objects.filter(id__lt=2).union( Publication.objects.filter(id__gt=5) ), required=False, ) class Meta: model = Article fields = ["publications"] class ArticleAdmin(admin.ModelAdmin): form = ArticleForm ``` To reproduce: 1. Create a Django form with a `ModelMultipleChoiceField` using a queryset created with `union()` method 2. Set `required=False` to allow empty selections 3. Submit the form without selecting any values 4. Observe that ALL objects from the queryset are added to the many-to-many relationship Internally, when an empty selection is submitted for a `ModelMultipleChoiceField`, Django calls `self.queryset.none()` to represent "no selections". However, with a union queryset, this `none()` operation doesn't properly propagate the "emptiness" status, resulting in all objects being added instead. ## Expected Behavior When submitting a form with no selections for a `ModelMultipleChoiceField`, no objects should be added to the many-to-many relationship, regardless of whether the queryset was created using `union()` or the OR operator (`|`). ## Exploration Hints ### Files to Examine: - `django/db/models/query.py` - Contains the `QuerySet` class with its `union()` and `none()` methods that are central to the issue. The bug likely involves how the "emptiness" property set by `none()` interacts with querysets combined via SQL combinators. - `django/forms/models.py` - Contains `ModelMultipleChoiceField` which calls `queryset.none()` when handling empty selections. - `django/db/models/sql/query.py` - Contains the core `Query` class that handles SQL generation for different query types. ### Key Classes/Functions: - `QuerySet.union()` - Creates a combined queryset using SQL UNION operations, handling empty querysets differently than the OR operator. - `QuerySet.none()` - Sets a queryset to return no results by calling `query.set_empty()`, but appears not to work correctly with union querysets. - `ModelMultipleChoiceField.clean()` - Returns `self.queryset.none()` when processing empty selections, which behaves differently based on how the queryset was constructed. - `QuerySet._combinator_query()` - The internal method that handles all SQL combinators (union, intersection, difference), likely needs to preserve "emptiness" status. ### Areas of Interest: - How the "emptiness" flag is preserved (or not) when combining querysets with SQL operations - Differences between SQL UNION operations and Python-level OR combinations - How Django's ORM translates empty querysets to SQL for different types of combined queries - The interaction between `none()` and queryset combining methods ## Fix Hints ### High Confidence Locations: - `QuerySet._combinator_query()` in `django/db/models/query.py` - This method needs to properly handle and preserve the "emptiness" property when combining querysets. - `QuerySet.none()` method implementation - May need to be updated to properly handle combined queries. ### Implementation Hints: - The fix likely involves ensuring that calling `none()` on a combined queryset (created via `union()`) properly propagates the emptiness flag through all layers. - Consider special handling in the `_combinator_query()` method for when `none()` is called on a union queryset. - Another approach might be to modify how `ModelMultipleChoiceField` handles empty selections with combined querysets, possibly treating them differently based on how they were constructed. ### Alternative Hypotheses: 1. The issue could be in the Django form processing code rather than the QuerySet class, specifically in how empty selections are interpreted for different types of querysets. 2. The bug might be related to evaluation timing - union querysets and OR querysets might be evaluated at different points during the form submission process. 3. The problem could be in the many-to-many relationship handling code that determines what objects to add/remove based on form submissions. 4. It might involve caching mechanisms that behave differently for SQL-combined queries versus Python-combined queries. 5. There could be a difference in how "emptiness" is detected or compared when determining changes to apply to the many-to-many relationship.
Thanks for the report. QuerySet.none() doesn't work properly on combined querysets, it returns all results instead of an empty queryset.
2020-07-06T19:18:11Z
3.2
["test_union_none (queries.test_qs_combinators.QuerySetSetOperationTests)"]
["test_combining_multiple_models (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_difference (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_intersection (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_union (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_union_empty_result (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_difference_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_difference_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_intersection_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_intersection_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_limits (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_order_by_same_type (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_order_raises_on_non_selected_column (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_ordering (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_ordering_by_alias (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_ordering_by_f_expression (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_ordering_by_f_expression_and_alias (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_qs_with_subcompound_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_simple_difference (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_simple_intersection (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_simple_union (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_distinct (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_empty_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_extra_and_values_list (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_two_annotated_values_list (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_values_list_and_order (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_union_with_values_list_on_annotated_and_unannotated (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_unsupported_operations_on_combined_qs (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_unsupported_ordering_slicing_raises_db_error (queries.test_qs_combinators.QuerySetSetOperationTests)"]
65dfb06a1ab56c238cc80f5e1c31f61210c4577d
django/django
django__django-14017
466920f6d726eee90d5566e0a9948e92b33a122e
diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py --- a/django/db/models/query_utils.py +++ b/django/db/models/query_utils.py @@ -40,7 +40,7 @@ def __init__(self, *args, _connector=None, _negated=False, **kwargs): super().__init__(children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated) def _combine(self, other, conn): - if not isinstance(other, Q): + if not(isinstance(other, Q) or getattr(other, 'conditional', False) is True): raise TypeError(other) # If the other Q() is empty, ignore it and just use `self`.
diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -815,6 +815,28 @@ def test_boolean_expression_combined(self): Employee.objects.filter(Exists(is_poc) | Q(salary__lt=15)), [self.example_inc.ceo, self.max], ) + self.assertCountEqual( + Employee.objects.filter(Q(salary__gte=30) & Exists(is_ceo)), + [self.max], + ) + self.assertCountEqual( + Employee.objects.filter(Q(salary__lt=15) | Exists(is_poc)), + [self.example_inc.ceo, self.max], + ) + + def test_boolean_expression_combined_with_empty_Q(self): + is_poc = Company.objects.filter(point_of_contact=OuterRef('pk')) + self.gmbh.point_of_contact = self.max + self.gmbh.save() + tests = [ + Exists(is_poc) & Q(), + Q() & Exists(is_poc), + Exists(is_poc) | Q(), + Q() | Exists(is_poc), + ] + for conditions in tests: + with self.subTest(conditions): + self.assertCountEqual(Employee.objects.filter(conditions), [self.max]) class IterableLookupInnerExpressionsTests(TestCase):
# Non-commutative behavior between Q objects and Exists expressions ## Issue Description Django ORM has an inconsistent behavior when combining `Q` objects and `Exists` expressions using the `&` (AND) operator. While `Exists(...) & Q()` works correctly, the reverse order `Q() & Exists(...)` raises a `TypeError`. This breaks the expected commutative property of logical AND operations, making query construction order-dependent and error-prone. The root cause is that the `Q._combine()` method explicitly checks if the other operand is a `Q` instance and raises a `TypeError` if not. Meanwhile, the `Exists` class appears to properly handle `Q` objects when it's on the left side of the operator, but there's no equivalent handling when `Exists` is on the right side of a `Q` object. ## Reproduction Steps ```python # This works fine Exists(Product.objects.all()) & Q() # Output: <Q: (AND: <django.db.models.expressions.Exists object at 0x7fc18dd0ed90>, (AND: ))> # This raises TypeError Q() & Exists(Product.objects.all()) # Raises: TypeError: <django.db.models.expressions.Exists object at 0x7fc18dd21400> ``` The error occurs because: 1. When executing `Q() & Exists(...)`, Python calls `Q.__and__(Exists(...))` 2. This method calls `Q._combine(Exists(...), self.AND)` 3. Inside `_combine()`, it checks `if not isinstance(other, Q):` which is true for an Exists object 4. It then raises `TypeError(other)`, showing the Exists object in the error message The stack trace points directly to the issue: ``` TypeError Traceback (most recent call last) <ipython-input-4-21d3dea0fcb9> in <module> ----> 1 Q() & Exists(Product.objects.all()) ~/Code/venv/ecom/lib/python3.8/site-packages/django/db/models/query_utils.py in __and__(self, other) 90 91 def __and__(self, other): ---> 92 return self._combine(other, self.AND) 93 94 def __invert__(self): ~/Code/venv/ecom/lib/python3.8/site-packages/django/db/models/query_utils.py in _combine(self, other, conn) 71 def _combine(self, other, conn): 72 if not isinstance(other, Q): ---> 73 raise TypeError(other) 74 75 # If the other Q() is empty, ignore it and just use `self`. ``` ## Expected Behavior Both `Exists(...) & Q()` and `Q() & Exists(...)` should work correctly and produce equivalent results, preserving the commutative property of the AND operation. The operation should combine the two expressions into a logical AND expression that can be used in ORM queries. ## Exploration Hints ### Files to Examine: - **django/db/models/query_utils.py** - Contains the `Q` class implementation, specifically the `_combine()` method that raises the TypeError. This is where the type check restricts combinations to only Q objects. - **django/db/models/expressions.py** - Contains the `Exists` class implementation which inherits from `Subquery`. The class needs examination to understand how it handles logical operations and whether it needs a `__rand__` method. ### Key Classes/Functions: - **Q._combine(other, conn)** - This method contains the problematic code that rejects non-Q objects. It needs modification to handle Exists objects or to properly defer to the other object's `__rand__` method. - **Q.__and__(other)** - Calls `_combine()` and is the entry point for the `&` operator when a Q object is on the left side. - **Exists class** - Needs investigation to determine if it has an `__and__` method that handles Q objects, and whether it needs a `__rand__` method for the reverse operation. ### Areas of Interest: - **Python's operator overloading mechanism** - When `a & b` is evaluated, Python first tries `a.__and__(b)`, and if that returns `NotImplemented`, it tries `b.__rand__(a)`. This explains why the operation works in one direction but not the other. - **Django ORM expression combining pattern** - The broader pattern of how different expression types are designed to interact with each other in Django's ORM. ## Fix Hints ### High Confidence Locations: - **Q._combine() method (lines 71-73)** - The type check is overly restrictive and prevents interoperability with other expression types: ```python def _combine(self, other, conn): if not isinstance(other, Q): raise TypeError(other) ``` ### Implementation Hints: 1. **Option 1: Modify Q._combine() to accept Exists objects** ```python def _combine(self, other, conn): from django.db.models.expressions import Exists if isinstance(other, (Q, Exists)): # Handle both Q and Exists objects # ... else: raise TypeError(other) ``` 2. **Option 2: Add a __rand__ method to the Exists class** ```python def __rand__(self, other): # Mirror the behavior of __and__ but from the right side # This would be called when Q() & Exists() is evaluated if isinstance(other, Q): return other.__and__(self) return NotImplemented ``` 3. **Option 3: Make Q._combine() return NotImplemented instead of raising TypeError** This would allow Python to try the `__rand__` method of the right operand: ```python def _combine(self, other, conn): if not isinstance(other, Q): return NotImplemented # Proceed with combining Q objects... ``` ### Alternative Hypotheses: 1. **Broader design issue** - This might be part of a larger architectural issue with how Django handles expression composition across different expression types. The fix might require a more comprehensive approach to ensure all expression types can be combined consistently. 2. **Intentional restriction** - There could be an intentional design decision to restrict certain combinations for SQL generation reasons, though this seems unlikely given that the operation works in the reverse order. 3. **Missing interface pattern** - The issue might indicate a need for a common interface or protocol that expressions should implement to be combinable, rather than relying on concrete type checking. 4. **Exists implementation issue** - The problem could be in how the Exists class implements its operator methods, potentially bypassing proper operator overloading protocols.
Reproduced on 3.1.6. The exception is raised by this two lines in the Q._combine, which are not present in the Combinable._combine from which Exists inherit. if not isinstance(other, Q): raise TypeError(other) Tests: diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index 08ea0a51d3..20d0404f44 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -815,6 +815,15 @@ class BasicExpressionsTests(TestCase): Employee.objects.filter(Exists(is_poc) | Q(salary__lt=15)), [self.example_inc.ceo, self.max], ) + self.assertCountEqual( + Employee.objects.filter(Q(salary__gte=30) & Exists(is_ceo)), + [self.max], + ) + self.assertCountEqual( + Employee.objects.filter(Q(salary__lt=15) | Exists(is_poc)), + [self.example_inc.ceo, self.max], + ) + class IterableLookupInnerExpressionsTests(TestCase): ​PR
2021-02-18T13:05:27Z
4.0
["test_boolean_expression_combined (expressions.tests.BasicExpressionsTests)", "test_boolean_expression_combined_with_empty_Q (expressions.tests.BasicExpressionsTests)"]
["test_resolve_output_field (expressions.tests.CombinedExpressionTests)", "test_deconstruct (expressions.tests.FTests)", "test_deepcopy (expressions.tests.FTests)", "test_equal (expressions.tests.FTests)", "test_hash (expressions.tests.FTests)", "test_not_equal_Value (expressions.tests.FTests)", "test_and (expressions.tests.CombinableTests)", "test_negation (expressions.tests.CombinableTests)", "test_or (expressions.tests.CombinableTests)", "test_reversed_and (expressions.tests.CombinableTests)", "test_reversed_or (expressions.tests.CombinableTests)", "test_empty_group_by (expressions.tests.ExpressionWrapperTests)", "test_non_empty_group_by (expressions.tests.ExpressionWrapperTests)", "test_aggregates (expressions.tests.ReprTests)", "test_distinct_aggregates (expressions.tests.ReprTests)", "test_expressions (expressions.tests.ReprTests)", "test_filtered_aggregates (expressions.tests.ReprTests)", "test_functions (expressions.tests.ReprTests)", "test_optimizations (expressions.tests.ExistsTests)", "test_equal (expressions.tests.SimpleExpressionTests)", "test_hash (expressions.tests.SimpleExpressionTests)", "test_month_aggregation (expressions.tests.FieldTransformTests)", "test_multiple_transforms_in_values (expressions.tests.FieldTransformTests)", "test_transform_in_values (expressions.tests.FieldTransformTests)", "Complex expressions of different connection types are possible.", "We can fill a value in all objects with an other value of the", "We can filter for objects, where a value is not equals the value", "We can increment a value of all objects in a query set.", "test_compile_unresolved (expressions.tests.ValueTests)", "test_deconstruct (expressions.tests.ValueTests)", "test_deconstruct_output_field (expressions.tests.ValueTests)", "test_equal (expressions.tests.ValueTests)", "test_equal_output_field (expressions.tests.ValueTests)", "test_hash (expressions.tests.ValueTests)", "test_raise_empty_expressionlist (expressions.tests.ValueTests)", "test_resolve_output_field (expressions.tests.ValueTests)", "test_resolve_output_field_failure (expressions.tests.ValueTests)", "test_update_TimeField_using_Value (expressions.tests.ValueTests)", "test_update_UUIDField_using_Value (expressions.tests.ValueTests)", "test_F_reuse (expressions.tests.ExpressionsTests)", "Special characters (e.g. %, _ and \\) stored in database are", "This tests that SQL injection isn't possible using compilation of", "test_expressions_in_lookups_join_choice (expressions.tests.IterableLookupInnerExpressionsTests)", "test_in_lookup_allows_F_expressions_and_expressions_for_datetimes (expressions.tests.IterableLookupInnerExpressionsTests)", "test_in_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)", "test_range_lookup_allows_F_expressions_and_expressions_for_integers (expressions.tests.IterableLookupInnerExpressionsTests)", "test_range_lookup_namedtuple (expressions.tests.IterableLookupInnerExpressionsTests)", "test_lefthand_addition (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_and (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_left_shift_operator (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_or (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_right_shift_operator (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_xor (expressions.tests.ExpressionOperatorTests)", "test_lefthand_bitwise_xor_null (expressions.tests.ExpressionOperatorTests)", "test_lefthand_division (expressions.tests.ExpressionOperatorTests)", "test_lefthand_modulo (expressions.tests.ExpressionOperatorTests)", "test_lefthand_multiplication (expressions.tests.ExpressionOperatorTests)", "test_lefthand_power (expressions.tests.ExpressionOperatorTests)", "test_lefthand_subtraction (expressions.tests.ExpressionOperatorTests)", "test_lefthand_transformed_field_bitwise_or (expressions.tests.ExpressionOperatorTests)", "test_right_hand_addition (expressions.tests.ExpressionOperatorTests)", "test_right_hand_division (expressions.tests.ExpressionOperatorTests)", "test_right_hand_modulo (expressions.tests.ExpressionOperatorTests)", "test_right_hand_multiplication (expressions.tests.ExpressionOperatorTests)", "test_right_hand_subtraction (expressions.tests.ExpressionOperatorTests)", "test_righthand_power (expressions.tests.ExpressionOperatorTests)", "test_date_case_subtraction (expressions.tests.FTimeDeltaTests)", "test_date_comparison (expressions.tests.FTimeDeltaTests)", "test_date_minus_duration (expressions.tests.FTimeDeltaTests)", "test_date_subquery_subtraction (expressions.tests.FTimeDeltaTests)", "test_date_subtraction (expressions.tests.FTimeDeltaTests)", "test_datetime_subquery_subtraction (expressions.tests.FTimeDeltaTests)", "test_datetime_subtraction (expressions.tests.FTimeDeltaTests)", "test_datetime_subtraction_microseconds (expressions.tests.FTimeDeltaTests)", "test_delta_add (expressions.tests.FTimeDeltaTests)", "test_delta_subtract (expressions.tests.FTimeDeltaTests)", "test_delta_update (expressions.tests.FTimeDeltaTests)", "test_duration_expressions (expressions.tests.FTimeDeltaTests)", "test_duration_with_datetime (expressions.tests.FTimeDeltaTests)", "test_duration_with_datetime_microseconds (expressions.tests.FTimeDeltaTests)", "test_durationfield_add (expressions.tests.FTimeDeltaTests)", "test_exclude (expressions.tests.FTimeDeltaTests)", "test_invalid_operator (expressions.tests.FTimeDeltaTests)", "test_mixed_comparisons2 (expressions.tests.FTimeDeltaTests)", "test_multiple_query_compilation (expressions.tests.FTimeDeltaTests)", "test_negative_timedelta_update (expressions.tests.FTimeDeltaTests)", "test_query_clone (expressions.tests.FTimeDeltaTests)", "test_time_subquery_subtraction (expressions.tests.FTimeDeltaTests)", "test_time_subtraction (expressions.tests.FTimeDeltaTests)", "test_aggregate_rawsql_annotation (expressions.tests.BasicExpressionsTests)", "test_aggregate_subquery_annotation (expressions.tests.BasicExpressionsTests)", "test_annotate_values_aggregate (expressions.tests.BasicExpressionsTests)", "test_annotate_values_count (expressions.tests.BasicExpressionsTests)", "test_annotate_values_filter (expressions.tests.BasicExpressionsTests)", "test_annotation_with_nested_outerref (expressions.tests.BasicExpressionsTests)", "test_annotation_with_outerref (expressions.tests.BasicExpressionsTests)", "test_annotations_within_subquery (expressions.tests.BasicExpressionsTests)", "test_arithmetic (expressions.tests.BasicExpressionsTests)", "test_case_in_filter_if_boolean_output_field (expressions.tests.BasicExpressionsTests)", "test_exist_single_field_output_field (expressions.tests.BasicExpressionsTests)", "test_exists_in_filter (expressions.tests.BasicExpressionsTests)", "test_explicit_output_field (expressions.tests.BasicExpressionsTests)", "test_filter_inter_attribute (expressions.tests.BasicExpressionsTests)", "test_filter_with_join (expressions.tests.BasicExpressionsTests)", "test_filtering_on_annotate_that_uses_q (expressions.tests.BasicExpressionsTests)", "test_filtering_on_q_that_is_boolean (expressions.tests.BasicExpressionsTests)", "test_filtering_on_rawsql_that_is_boolean (expressions.tests.BasicExpressionsTests)", "test_in_subquery (expressions.tests.BasicExpressionsTests)", "test_incorrect_field_in_F_expression (expressions.tests.BasicExpressionsTests)", "test_incorrect_joined_field_in_F_expression (expressions.tests.BasicExpressionsTests)", "test_nested_outerref_with_function (expressions.tests.BasicExpressionsTests)", "test_nested_subquery (expressions.tests.BasicExpressionsTests)", "test_nested_subquery_join_outer_ref (expressions.tests.BasicExpressionsTests)", "test_nested_subquery_outer_ref_2 (expressions.tests.BasicExpressionsTests)", "test_nested_subquery_outer_ref_with_autofield (expressions.tests.BasicExpressionsTests)", "test_new_object_create (expressions.tests.BasicExpressionsTests)", "test_new_object_save (expressions.tests.BasicExpressionsTests)", "test_object_create_with_aggregate (expressions.tests.BasicExpressionsTests)", "test_object_update (expressions.tests.BasicExpressionsTests)", "test_object_update_fk (expressions.tests.BasicExpressionsTests)", "test_object_update_unsaved_objects (expressions.tests.BasicExpressionsTests)", "test_order_by_exists (expressions.tests.BasicExpressionsTests)", "test_order_by_multiline_sql (expressions.tests.BasicExpressionsTests)", "test_order_of_operations (expressions.tests.BasicExpressionsTests)", "test_outerref (expressions.tests.BasicExpressionsTests)", "test_outerref_mixed_case_table_name (expressions.tests.BasicExpressionsTests)", "test_outerref_with_operator (expressions.tests.BasicExpressionsTests)", "test_parenthesis_priority (expressions.tests.BasicExpressionsTests)", "test_pickle_expression (expressions.tests.BasicExpressionsTests)", "test_subquery (expressions.tests.BasicExpressionsTests)", "test_subquery_eq (expressions.tests.BasicExpressionsTests)", "test_subquery_filter_by_aggregate (expressions.tests.BasicExpressionsTests)", "test_subquery_filter_by_lazy (expressions.tests.BasicExpressionsTests)", "test_subquery_group_by_outerref_in_filter (expressions.tests.BasicExpressionsTests)", "test_subquery_in_filter (expressions.tests.BasicExpressionsTests)", "test_subquery_references_joined_table_twice (expressions.tests.BasicExpressionsTests)", "test_ticket_11722_iexact_lookup (expressions.tests.BasicExpressionsTests)", "test_ticket_16731_startswith_lookup (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_chained_filters (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_join_reuse (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_kwarg_ordering (expressions.tests.BasicExpressionsTests)", "test_ticket_18375_kwarg_ordering_2 (expressions.tests.BasicExpressionsTests)", "test_update (expressions.tests.BasicExpressionsTests)", "test_update_inherited_field_value (expressions.tests.BasicExpressionsTests)", "test_update_with_fk (expressions.tests.BasicExpressionsTests)", "test_update_with_none (expressions.tests.BasicExpressionsTests)", "test_uuid_pk_subquery (expressions.tests.BasicExpressionsTests)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django/django
django__django-14155
2f13c476abe4ba787b6cb71131818341911f43cc
diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py --- a/django/urls/resolvers.py +++ b/django/urls/resolvers.py @@ -59,9 +59,16 @@ def __getitem__(self, index): return (self.func, self.args, self.kwargs)[index] def __repr__(self): - return "ResolverMatch(func=%s, args=%s, kwargs=%s, url_name=%s, app_names=%s, namespaces=%s, route=%s)" % ( - self._func_path, self.args, self.kwargs, self.url_name, - self.app_names, self.namespaces, self.route, + if isinstance(self.func, functools.partial): + func = repr(self.func) + else: + func = self._func_path + return ( + 'ResolverMatch(func=%s, args=%r, kwargs=%r, url_name=%r, ' + 'app_names=%r, namespaces=%r, route=%r)' % ( + func, self.args, self.kwargs, self.url_name, + self.app_names, self.namespaces, self.route, + ) )
diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py --- a/tests/urlpatterns_reverse/tests.py +++ b/tests/urlpatterns_reverse/tests.py @@ -1141,10 +1141,30 @@ def test_repr(self): self.assertEqual( repr(resolve('/no_kwargs/42/37/')), "ResolverMatch(func=urlpatterns_reverse.views.empty_view, " - "args=('42', '37'), kwargs={}, url_name=no-kwargs, app_names=[], " - "namespaces=[], route=^no_kwargs/([0-9]+)/([0-9]+)/$)", + "args=('42', '37'), kwargs={}, url_name='no-kwargs', app_names=[], " + "namespaces=[], route='^no_kwargs/([0-9]+)/([0-9]+)/$')", ) + @override_settings(ROOT_URLCONF='urlpatterns_reverse.urls') + def test_repr_functools_partial(self): + tests = [ + ('partial', 'template.html'), + ('partial_nested', 'nested_partial.html'), + ('partial_wrapped', 'template.html'), + ] + for name, template_name in tests: + with self.subTest(name=name): + func = ( + f"functools.partial({views.empty_view!r}, " + f"template_name='{template_name}')" + ) + self.assertEqual( + repr(resolve(f'/{name}/')), + f"ResolverMatch(func={func}, args=(), kwargs={{}}, " + f"url_name='{name}', app_names=[], namespaces=[], " + f"route='{name}/')", + ) + @override_settings(ROOT_URLCONF='urlpatterns_reverse.erroneous_urls') class ErroneousViewTests(SimpleTestCase):
ResolverMatch.__repr__() doesn't handle functools.partial() nicely. Description (last modified by Nick Pope) When a partial function is passed as the view, the __repr__ shows the func argument as functools.partial which isn't very helpful, especially as it doesn't reveal the underlying function or arguments provided. Because a partial function also has arguments provided up front, we need to handle those specially so that they are accessible in __repr__. ISTM that we can simply unwrap functools.partial objects in ResolverMatch.__init__().
2021-03-19T15:44:25Z
4.0
["test_repr (urlpatterns_reverse.tests.ResolverMatchTests)", "test_repr_functools_partial (urlpatterns_reverse.tests.ResolverMatchTests)", "test_resolver_match_on_request (urlpatterns_reverse.tests.ResolverMatchTests)"]
["test_include_2_tuple (urlpatterns_reverse.tests.IncludeTests)", "test_include_2_tuple_namespace (urlpatterns_reverse.tests.IncludeTests)", "test_include_3_tuple (urlpatterns_reverse.tests.IncludeTests)", "test_include_3_tuple_namespace (urlpatterns_reverse.tests.IncludeTests)", "test_include_4_tuple (urlpatterns_reverse.tests.IncludeTests)", "test_include_app_name (urlpatterns_reverse.tests.IncludeTests)", "test_include_app_name_namespace (urlpatterns_reverse.tests.IncludeTests)", "test_include_namespace (urlpatterns_reverse.tests.IncludeTests)", "test_include_urls (urlpatterns_reverse.tests.IncludeTests)", "URLResolver should raise an exception when no urlpatterns exist.", "test_invalid_regex (urlpatterns_reverse.tests.ErroneousViewTests)", "test_noncallable_view (urlpatterns_reverse.tests.ErroneousViewTests)", "test_attributeerror_not_hidden (urlpatterns_reverse.tests.ViewLoadingTests)", "test_module_does_not_exist (urlpatterns_reverse.tests.ViewLoadingTests)", "test_non_string_value (urlpatterns_reverse.tests.ViewLoadingTests)", "test_not_callable (urlpatterns_reverse.tests.ViewLoadingTests)", "test_parent_module_does_not_exist (urlpatterns_reverse.tests.ViewLoadingTests)", "test_string_without_dot (urlpatterns_reverse.tests.ViewLoadingTests)", "test_view_does_not_exist (urlpatterns_reverse.tests.ViewLoadingTests)", "test_view_loading (urlpatterns_reverse.tests.ViewLoadingTests)", "test_callable_handlers (urlpatterns_reverse.tests.ErrorHandlerResolutionTests)", "test_named_handlers (urlpatterns_reverse.tests.ErrorHandlerResolutionTests)", "test_invalid_resolve (urlpatterns_reverse.tests.LookaheadTests)", "test_invalid_reverse (urlpatterns_reverse.tests.LookaheadTests)", "test_valid_resolve (urlpatterns_reverse.tests.LookaheadTests)", "test_valid_reverse (urlpatterns_reverse.tests.LookaheadTests)", "test_no_illegal_imports (urlpatterns_reverse.tests.ReverseShortcutTests)", "test_redirect_to_object (urlpatterns_reverse.tests.ReverseShortcutTests)", "test_redirect_to_url (urlpatterns_reverse.tests.ReverseShortcutTests)", "test_redirect_to_view_name (urlpatterns_reverse.tests.ReverseShortcutTests)", "test_redirect_view_object (urlpatterns_reverse.tests.ReverseShortcutTests)", "test_reverse_by_path_nested (urlpatterns_reverse.tests.ReverseShortcutTests)", "test_resolver_match_on_request_before_resolution (urlpatterns_reverse.tests.ResolverMatchTests)", "test_urlpattern_resolve (urlpatterns_reverse.tests.ResolverMatchTests)", "test_illegal_args_message (urlpatterns_reverse.tests.URLPatternReverse)", "test_illegal_kwargs_message (urlpatterns_reverse.tests.URLPatternReverse)", "test_mixing_args_and_kwargs (urlpatterns_reverse.tests.URLPatternReverse)", "test_no_args_message (urlpatterns_reverse.tests.URLPatternReverse)", "test_non_urlsafe_prefix_with_args (urlpatterns_reverse.tests.URLPatternReverse)", "test_patterns_reported (urlpatterns_reverse.tests.URLPatternReverse)", "test_prefix_braces (urlpatterns_reverse.tests.URLPatternReverse)", "test_prefix_format_char (urlpatterns_reverse.tests.URLPatternReverse)", "test_prefix_parenthesis (urlpatterns_reverse.tests.URLPatternReverse)", "test_reverse_none (urlpatterns_reverse.tests.URLPatternReverse)", "test_script_name_escaping (urlpatterns_reverse.tests.URLPatternReverse)", "test_urlpattern_reverse (urlpatterns_reverse.tests.URLPatternReverse)", "test_view_not_found_message (urlpatterns_reverse.tests.URLPatternReverse)", "test_build_absolute_uri (urlpatterns_reverse.tests.ReverseLazyTest)", "test_inserting_reverse_lazy_into_string (urlpatterns_reverse.tests.ReverseLazyTest)", "test_redirect_with_lazy_reverse (urlpatterns_reverse.tests.ReverseLazyTest)", "test_user_permission_with_lazy_reverse (urlpatterns_reverse.tests.ReverseLazyTest)", "Names deployed via dynamic URL objects that require namespaces can't", "A default application namespace can be used for lookup.", "A default application namespace is sensitive to the current app.", "An application namespace without a default is sensitive to the current", "Namespaces can be applied to include()'d urlpatterns that set an", "Dynamic URL objects can return a (pattern, app_name) 2-tuple, and", "Namespace defaults to app_name when including a (pattern, app_name)", "current_app shouldn't be used unless it matches the whole path.", "Namespaces can be installed anywhere in the URL pattern tree.", "Namespaces can be embedded.", "Dynamic URL objects can be found using a namespace.", "Namespaces can be applied to include()'d urlpatterns.", "Using include() with namespaces when there is a regex variable in front", "Namespace prefixes can capture variables.", "A nested current_app should be split in individual namespaces (#24904).", "Namespaces can be nested.", "Nonexistent namespaces raise errors.", "Normal lookups work as expected.", "Normal lookups work on names included from other patterns.", "test_special_chars_namespace (urlpatterns_reverse.tests.NamespaceTests)", "The list of URLs that come back from a Resolver404 exception contains", "test_namespaced_view_detail (urlpatterns_reverse.tests.ResolverTests)", "A Resolver404 is raised if resolving doesn't meet the basic", "URLResolver._populate() can be called concurrently, but not more", "Test repr of URLResolver, especially when urlconf_name is a list", "test_resolver_reverse (urlpatterns_reverse.tests.ResolverTests)", "URL pattern name arguments don't need to be unique. The last registered", "Verifies lazy object returned by reverse_lazy is coerced to", "test_view_detail_as_method (urlpatterns_reverse.tests.ResolverTests)", "Test reversing an URL from the *overridden* URLconf from inside", "Test reversing an URL from the *default* URLconf from inside", "test_urlconf (urlpatterns_reverse.tests.RequestURLconfTests)", "The URLconf is reset after each request.", "test_urlconf_overridden (urlpatterns_reverse.tests.RequestURLconfTests)", "Overriding request.urlconf with None will fall back to the default", "test_no_handler_exception (urlpatterns_reverse.tests.NoRootUrlConfTests)", "If the urls.py doesn't specify handlers, the defaults are used", "test_lazy_in_settings (urlpatterns_reverse.tests.ReverseLazySettingsTest)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django/django
django__django-14730
4fe3774c729f3fd5105b3001fe69a70bdca95ac3
diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -1258,6 +1258,16 @@ def _check_ignored_options(self, **kwargs): ) ) + if self.remote_field.symmetrical and self._related_name: + warnings.append( + checks.Warning( + 'related_name has no effect on ManyToManyField ' + 'with a symmetrical relationship, e.g. to "self".', + obj=self, + id='fields.W345', + ) + ) + return warnings def _check_relationship_model(self, from_model=None, **kwargs):
diff --git a/tests/field_deconstruction/tests.py b/tests/field_deconstruction/tests.py --- a/tests/field_deconstruction/tests.py +++ b/tests/field_deconstruction/tests.py @@ -438,7 +438,6 @@ class MyModel(models.Model): m2m = models.ManyToManyField('self') m2m_related_name = models.ManyToManyField( 'self', - related_name='custom_name', related_query_name='custom_query_name', limit_choices_to={'flag': True}, ) @@ -455,7 +454,6 @@ class MyModel(models.Model): self.assertEqual(args, []) self.assertEqual(kwargs, { 'to': 'field_deconstruction.MyModel', - 'related_name': 'custom_name', 'related_query_name': 'custom_query_name', 'limit_choices_to': {'flag': True}, }) diff --git a/tests/invalid_models_tests/test_relative_fields.py b/tests/invalid_models_tests/test_relative_fields.py --- a/tests/invalid_models_tests/test_relative_fields.py +++ b/tests/invalid_models_tests/test_relative_fields.py @@ -128,6 +128,20 @@ class ThroughModel(models.Model): ), ]) + def test_many_to_many_with_useless_related_name(self): + class ModelM2M(models.Model): + m2m = models.ManyToManyField('self', related_name='children') + + field = ModelM2M._meta.get_field('m2m') + self.assertEqual(ModelM2M.check(), [ + DjangoWarning( + 'related_name has no effect on ManyToManyField with ' + 'a symmetrical relationship, e.g. to "self".', + obj=field, + id='fields.W345', + ), + ]) + def test_ambiguous_relationship_model_from(self): class Person(models.Model): pass diff --git a/tests/model_meta/models.py b/tests/model_meta/models.py --- a/tests/model_meta/models.py +++ b/tests/model_meta/models.py @@ -23,7 +23,7 @@ class AbstractPerson(models.Model): # M2M fields m2m_abstract = models.ManyToManyField(Relation, related_name='m2m_abstract_rel') - friends_abstract = models.ManyToManyField('self', related_name='friends_abstract', symmetrical=True) + friends_abstract = models.ManyToManyField('self', symmetrical=True) following_abstract = models.ManyToManyField('self', related_name='followers_abstract', symmetrical=False) # VIRTUAL fields @@ -60,7 +60,7 @@ class BasePerson(AbstractPerson): # M2M fields m2m_base = models.ManyToManyField(Relation, related_name='m2m_base_rel') - friends_base = models.ManyToManyField('self', related_name='friends_base', symmetrical=True) + friends_base = models.ManyToManyField('self', symmetrical=True) following_base = models.ManyToManyField('self', related_name='followers_base', symmetrical=False) # VIRTUAL fields @@ -88,7 +88,7 @@ class Person(BasePerson): # M2M Fields m2m_inherited = models.ManyToManyField(Relation, related_name='m2m_concrete_rel') - friends_inherited = models.ManyToManyField('self', related_name='friends_concrete', symmetrical=True) + friends_inherited = models.ManyToManyField('self', symmetrical=True) following_inherited = models.ManyToManyField('self', related_name='followers_concrete', symmetrical=False) # VIRTUAL fields
# Enhanced Problem Statement: ManyToManyField Validation for Symmetrical Relationships ## Issue Description Django's `ManyToManyField` currently does not validate when developers specify a `related_name` parameter on symmetrical many-to-many relationships. In symmetrical relationships (either explicitly with `symmetrical=True` or implicitly through self-reference), Django does not create the related field on the target model, meaning any specified `related_name` is silently ignored. The code automatically overrides user-provided `related_name` values with an auto-generated name (`"%s_rel_+" % name`) without warning, leading to developer confusion. This issue requires adding validation to alert developers when they attempt to set a `related_name` that will have no effect. ## Reproduction Steps 1. Create a model with a symmetrical `ManyToManyField` and a `related_name`: ```python from django.db import models class Person(models.Model): name = models.CharField(max_length=100) # Either of these will reproduce the issue: # Option 1: Self-referential (implicitly symmetrical) with related_name friends = models.ManyToManyField('self', related_name='friend_of') # Option 2: Explicitly symmetrical with related_name connections = models.ManyToManyField('self', symmetrical=True, related_name='connected_to') ``` 2. The field initialization proceeds without error, but internally: - The `ManyToManyField.contribute_to_class` method detects the symmetrical relationship - It silently replaces the user-specified `related_name` with an auto-generated pattern (`"%s_rel_+" % name`) - No warning is shown to the developer that their `related_name` parameter is being ignored 3. Later, when the developer tries to use the `friend_of` or `connected_to` accessors, they will not exist, potentially leading to confusion. ## Expected Behavior Django should validate and raise a clear error during model validation when a developer attempts to specify a `related_name` on a symmetrical `ManyToManyField`. The error should explain that `related_name` has no effect on symmetrical relationships since no backward relation is created, and suggest either removing the `related_name` parameter or setting `symmetrical=False` if a non-symmetrical relationship is desired. ## Exploration Hints ### Files to Examine: - `django/db/models/fields/related.py` - Contains the `ManyToManyField` class implementation, including relationship configuration logic - `django/core/checks/fields.py` - Contains field validation checks that get executed during Django's system check framework ### Key Classes/Functions: - `ManyToManyField.__init__()` - Constructor that accepts and stores the `related_name` and `symmetrical` parameters - `ManyToManyField.contribute_to_class()` - Handles setting up the many-to-many relationship and silently overrides `related_name` for symmetrical relationships - `ManyToManyField._check_ignored_options()` - Designed to validate and warn about parameter combinations that lead to ignored options; ideal place to add the validation logic - `ManyToManyField.check()` - Entry point for Django's validation system that calls specific check methods ### Areas of Interest: - The code that detects symmetrical relationships, which happens in two ways: 1. When `symmetrical=True` is explicitly provided 2. When the relationship is self-referential (`to` is `'self'` or the same model class) and `symmetrical` isn't explicitly set to `False` - The current handling of `related_name` in symmetrical relationships, where it's automatically set to a pattern like `"{field_name}_rel_+"` regardless of user input ## Fix Hints ### High Confidence Locations: - `ManyToManyField._check_ignored_options()` - This is the ideal place to add validation as it's specifically designed to check for ignored parameters and already returns Django system check errors ### Implementation Hints: - Add code to detect when both conditions are true: 1. The relationship is symmetrical (either explicitly or implicitly) 2. A custom `related_name` was specified by the user (not None or the default) - Return a `CheckMessage` error with a clear explanation about why `related_name` doesn't apply to symmetrical relationships - The validation should happen during Django's system check framework execution, not at runtime ```python def _check_ignored_options(self): errors = super()._check_ignored_options() # Check for related_name on symmetrical relationships if self.remote_field.symmetrical and self.remote_field.related_name not in (None, '+'): errors.append( checks.Error( 'related_name has no effect on ManyToManyField with symmetrical=True.', hint='Remove related_name as it is ignored in this case.', obj=self, id='fields.E330', # Choose an appropriate error ID ) ) return errors ``` ### Alternative Hypotheses: 1. Instead of raising an error, Django could silently ignore the `related_name` and add documentation about this behavior - this would maintain backward compatibility but wouldn't solve the developer confusion issue 2. There might be edge cases where specifying a `related_name` on symmetrical relationships could be useful, particularly with custom `through` models or complex queries, though the current code doesn't indicate this 3. The check could be implemented as a warning instead of an error, allowing developers to acknowledge the issue but proceed if they have a specific reason for the configuration
I have a PR that implements this incoming. ​https://github.com/django/django/pull/14730 OK, I guess we can do something here — it probably is a source of confusion. The same issue was raised in #18021 (but as an invalid bug report, rather than suggesting improving the messaging). Looking at the PR — I'm sceptical about just raising an error — this will likely break code in the wild. Can we investigate adding a system check here instead? There are several similar checks for related fields already: ​https://docs.djangoproject.com/en/3.2/ref/checks/#related-fields Same issue also came up in #12641 Absolutely. A system check is a much better approach than my initial idea of the error. I have changed the patch to use a system check. Unchecking patch needs improvement as instructed on the page, (pending reviewer acceptance of course).
2021-08-03T04:27:52Z
4.0
["test_many_to_many_with_useless_related_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)"]
["test_accessor_clash (invalid_models_tests.test_relative_fields.SelfReferentialFKClashTests)", "test_clash_under_explicit_related_name (invalid_models_tests.test_relative_fields.SelfReferentialFKClashTests)", "test_reverse_query_name_clash (invalid_models_tests.test_relative_fields.SelfReferentialFKClashTests)", "test_clash_parent_link (invalid_models_tests.test_relative_fields.ComplexClashTests)", "test_complex_clash (invalid_models_tests.test_relative_fields.ComplexClashTests)", "If ``through_fields`` kwarg is given, it must specify both", "test_intersection_foreign_object (invalid_models_tests.test_relative_fields.M2mThroughFieldsTests)", "Providing invalid field names to ManyToManyField.through_fields", "Mixing up the order of link fields to ManyToManyField.through_fields", "ManyToManyField accepts the ``through_fields`` kwarg", "test_superset_foreign_object (invalid_models_tests.test_relative_fields.M2mThroughFieldsTests)", "test_accessor_clash (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)", "test_clash_between_accessors (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)", "test_clash_under_explicit_related_name (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)", "test_reverse_query_name_clash (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)", "test_valid_model (invalid_models_tests.test_relative_fields.SelfReferentialM2MClashTests)", "test_fk_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_fk_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_fk_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_m2m_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_m2m_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_m2m_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedNameClashTests)", "test_fk_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_fk_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_fk_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_fk_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_fk_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_fk_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_m2m_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_m2m_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_hidden_m2m_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_m2m_to_fk (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_m2m_to_integer (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_m2m_to_m2m (invalid_models_tests.test_relative_fields.ExplicitRelatedQueryNameClashTests)", "test_clash_between_accessors (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_fk_to_fk (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_fk_to_integer (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_fk_to_m2m (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_m2m_to_fk (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_m2m_to_integer (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_m2m_to_m2m (invalid_models_tests.test_relative_fields.AccessorClashTests)", "Ref #22047.", "test_no_clash_for_hidden_related_name (invalid_models_tests.test_relative_fields.AccessorClashTests)", "test_fk_to_fk (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_fk_to_integer (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_fk_to_m2m (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_m2m_to_fk (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_m2m_to_integer (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_m2m_to_m2m (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_no_clash_across_apps_without_accessor (invalid_models_tests.test_relative_fields.ReverseQueryNameClashTests)", "test_ambiguous_relationship_model_from (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_ambiguous_relationship_model_to (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_key_to_abstract_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "#25723 - Referenced model registration lookup should be run against the", "test_foreign_key_to_missing_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_key_to_non_unique_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_key_to_non_unique_field_under_explicit_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_key_to_partially_unique_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_key_to_unique_field_with_meta_constraint (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_object_to_non_unique_fields (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_object_to_partially_unique_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_foreign_object_to_unique_field_with_meta_constraint (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_invalid_related_query_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_m2m_to_abstract_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "#25723 - Through model registration lookup should be run against the", "test_many_to_many_to_missing_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_many_to_many_with_limit_choices_auto_created_no_warning (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_many_to_many_with_useless_options (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_missing_relationship_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_missing_relationship_model_on_model_check (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_not_swapped_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_nullable_primary_key (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_on_delete_set_default_without_default_value (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_on_delete_set_null_on_non_nullable_field (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_referencing_to_swapped_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_related_field_has_invalid_related_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_related_field_has_valid_related_name (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_relationship_model_missing_foreign_key (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_relationship_model_with_foreign_key_to_wrong_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_to_fields_exist (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_to_fields_not_checked_if_related_model_doesnt_exist (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_too_many_foreign_keys_in_self_referential_model (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_unique_m2m (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_valid_foreign_key_without_accessor (invalid_models_tests.test_relative_fields.RelativeFieldTests)", "test_auto_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_big_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_binary_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_boolean_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_char_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_char_field_choices (field_deconstruction.tests.FieldDeconstructionTests)", "test_csi_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_date_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_datetime_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_db_tablespace (field_deconstruction.tests.FieldDeconstructionTests)", "test_decimal_field (field_deconstruction.tests.FieldDeconstructionTests)", "A DecimalField with decimal_places=0 should work (#22272).", "test_email_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_file_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_file_path_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_float_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_foreign_key (field_deconstruction.tests.FieldDeconstructionTests)", "test_foreign_key_swapped (field_deconstruction.tests.FieldDeconstructionTests)", "test_generic_ip_address_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_image_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_ip_address_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_many_to_many_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_many_to_many_field_related_name (field_deconstruction.tests.FieldDeconstructionTests)", "test_many_to_many_field_swapped (field_deconstruction.tests.FieldDeconstructionTests)", "Tests the outputting of the correct name if assigned one.", "test_one_to_one (field_deconstruction.tests.FieldDeconstructionTests)", "test_positive_big_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_positive_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_positive_small_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_slug_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_small_integer_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_text_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_time_field (field_deconstruction.tests.FieldDeconstructionTests)", "test_url_field (field_deconstruction.tests.FieldDeconstructionTests)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django/django
django__django-15789
d4d5427571b4bf3a21c902276c2a00215c2a37cc
diff --git a/django/utils/html.py b/django/utils/html.py --- a/django/utils/html.py +++ b/django/utils/html.py @@ -59,7 +59,7 @@ def escapejs(value): } -def json_script(value, element_id=None): +def json_script(value, element_id=None, encoder=None): """ Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. Wrap @@ -67,7 +67,9 @@ def json_script(value, element_id=None): """ from django.core.serializers.json import DjangoJSONEncoder - json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes) + json_str = json.dumps(value, cls=encoder or DjangoJSONEncoder).translate( + _json_script_escapes + ) if element_id: template = '<script id="{}" type="application/json">{}</script>' args = (element_id, mark_safe(json_str))
diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py --- a/tests/utils_tests/test_html.py +++ b/tests/utils_tests/test_html.py @@ -1,6 +1,7 @@ import os from datetime import datetime +from django.core.serializers.json import DjangoJSONEncoder from django.test import SimpleTestCase from django.utils.functional import lazystr from django.utils.html import ( @@ -211,6 +212,16 @@ def test_json_script(self): with self.subTest(arg=arg): self.assertEqual(json_script(arg, "test_id"), expected) + def test_json_script_custom_encoder(self): + class CustomDjangoJSONEncoder(DjangoJSONEncoder): + def encode(self, o): + return '{"hello": "world"}' + + self.assertHTMLEqual( + json_script({}, encoder=CustomDjangoJSONEncoder), + '<script type="application/json">{"hello": "world"}</script>', + ) + def test_json_script_without_id(self): self.assertHTMLEqual( json_script({"key": "value"}),
# Enhanced Problem Statement: Add encoder parameter to django.utils.html.json_script() ## Issue Description The `django.utils.html.json_script()` utility function currently uses a hardcoded `DjangoJSONEncoder` class for JSON serialization, which prevents developers from customizing how values are encoded when embedding JSON data in HTML templates. This limitation makes it difficult to handle custom data types or override serialization behavior for specific use cases. The function needs an optional `encoder` parameter to allow for custom JSON encoders, following Django's established pattern of encoder customization seen elsewhere in the framework. Additionally, the `json_script()` function itself is not documented in Django's official documentation, despite having a documented template filter counterpart. ## Reproduction Steps There's no error to reproduce, but the current limitation can be demonstrated by attempting to use a custom encoder with `json_script()`: ```python from django.utils.html import json_script from django.core.serializers.json import DjangoJSONEncoder class CustomJSONEncoder(DjangoJSONEncoder): def default(self, obj): # Custom encoding logic for specific types if isinstance(obj, MyCustomType): return obj.to_dict() return super().default(obj) # Current approach - cannot pass custom encoder json_script(my_data, "data-id") # Uses hardcoded DjangoJSONEncoder # Desired approach - not currently possible # json_script(my_data, "data-id", encoder=CustomJSONEncoder) ``` Currently, developers must pre-process their data with custom encoding before passing it to `json_script()`, which is less convenient and may require duplicating functionality already provided by Django's encoder system. ## Expected Behavior The `json_script()` function should accept an optional `encoder` parameter that defaults to `DjangoJSONEncoder` to maintain backward compatibility. The JSON serialization logic within the function should use the provided encoder instead of hardcoding `DjangoJSONEncoder`. This would align with Django's pattern for encoder customization seen in other parts of the framework, such as in `django.core.serializers.json.Serializer`. ## Exploration Hints ### Files to Examine: - **django/utils/html.py** - Contains the `json_script()` function that needs modification. This is where the hardcoded `DjangoJSONEncoder` usage needs to be replaced with a parameter-based approach. - **django/core/serializers/json.py** - Contains the `DjangoJSONEncoder` class and demonstrates Django's pattern for encoder customization in the `Serializer` class. - **django/template/defaultfilters.py** - May contain the template filter counterpart of `json_script()`, which should be examined to ensure consistency. ### Key Classes/Functions: - **json_script(value, element_id)** - The function to modify. Currently converts Python values to JSON using the hardcoded `DjangoJSONEncoder` and wraps the result in an HTML script tag. - **DjangoJSONEncoder** - Django's default JSON encoder that handles special types (datetime, UUID, Decimal, etc.). Any custom encoder would likely need to inherit from this class. ### Areas of Interest: - Django's JSON serialization pattern typically provides default behavior with `DjangoJSONEncoder` but allows customization through optional parameters. - The `json_script()` function uses `mark_safe()` to prevent further HTML escaping of its output, which has security implications that must be maintained. - Security considerations when embedding JSON in HTML templates, including proper escaping of special characters to prevent XSS vulnerabilities. ## Fix Hints ### High Confidence Locations: - The `json_script()` function in **django/utils/html.py** is the primary location for the fix. The function signature needs to be updated to include an optional encoder parameter. ### Implementation Hints: 1. Modify the function signature to: `json_script(value, element_id, encoder=DjangoJSONEncoder)` 2. Update the JSON serialization logic to use the provided encoder class 3. Ensure backward compatibility by defaulting to `DjangoJSONEncoder` 4. Add appropriate docstring documentation for the new parameter 5. Consider updating the template filter counterpart to pass through the encoder parameter if applicable Example implementation approach: ```python def json_script(value, element_id, encoder=DjangoJSONEncoder): """ Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. Turn the escaped string into a JSON string, and wrap it in a script tag. """ json_str = json.dumps(value, cls=encoder) # ... rest of the function remains the same ``` ### Alternative Hypotheses: 1. **Pre-processing approach**: Instead of modifying the function, users could pre-process their data with a custom encoder before passing to `json_script()`. However, this is less convenient and may require duplicating functionality. 2. **Template filter enhancement**: The template filter counterpart might already support custom encoders or could be enhanced instead, though consistency between both implementations would be preferable. 3. **Security considerations**: There might be security implications to allowing custom encoders that need careful examination, particularly since this function handles embedding data in HTML. 4. **Documentation focus**: Since the function is not documented, documenting it properly might be equally important as adding the encoder parameter.
Sounds good, and yes, we should document django.utils.html.json_script(). ​PR I'll also add docs for json_script() soon ​PR
2022-06-23T08:59:04Z
4.2
["test_json_script_custom_encoder (utils_tests.test_html.TestUtilsHtml)"]
["test_conditional_escape (utils_tests.test_html.TestUtilsHtml)", "test_escape (utils_tests.test_html.TestUtilsHtml)", "test_escapejs (utils_tests.test_html.TestUtilsHtml)", "test_format_html (utils_tests.test_html.TestUtilsHtml)", "test_html_safe (utils_tests.test_html.TestUtilsHtml)", "test_html_safe_defines_html_error (utils_tests.test_html.TestUtilsHtml)", "test_html_safe_doesnt_define_str (utils_tests.test_html.TestUtilsHtml)", "test_html_safe_subclass (utils_tests.test_html.TestUtilsHtml)", "test_json_script (utils_tests.test_html.TestUtilsHtml)", "test_json_script_without_id (utils_tests.test_html.TestUtilsHtml)", "test_linebreaks (utils_tests.test_html.TestUtilsHtml)", "test_smart_urlquote (utils_tests.test_html.TestUtilsHtml)", "test_strip_spaces_between_tags (utils_tests.test_html.TestUtilsHtml)", "test_strip_tags (utils_tests.test_html.TestUtilsHtml)", "test_strip_tags_files (utils_tests.test_html.TestUtilsHtml)", "test_urlize (utils_tests.test_html.TestUtilsHtml)", "test_urlize_unchanged_inputs (utils_tests.test_html.TestUtilsHtml)"]
0fbdb9784da915fce5dcc1fe82bac9b4785749e5
django/django
django__django-15400
4c76ffc2d6c77c850b4bef8d9acc197d11c47937
diff --git a/django/utils/functional.py b/django/utils/functional.py --- a/django/utils/functional.py +++ b/django/utils/functional.py @@ -432,6 +432,12 @@ def __deepcopy__(self, memo): return result return copy.deepcopy(self._wrapped, memo) + __add__ = new_method_proxy(operator.add) + + @new_method_proxy + def __radd__(self, other): + return other + self + def partition(predicate, values): """
diff --git a/tests/utils_tests/test_lazyobject.py b/tests/utils_tests/test_lazyobject.py --- a/tests/utils_tests/test_lazyobject.py +++ b/tests/utils_tests/test_lazyobject.py @@ -317,6 +317,17 @@ def test_repr(self): self.assertIsInstance(obj._wrapped, int) self.assertEqual(repr(obj), "<SimpleLazyObject: 42>") + def test_add(self): + obj1 = self.lazy_wrap(1) + self.assertEqual(obj1 + 1, 2) + obj2 = self.lazy_wrap(2) + self.assertEqual(obj2 + obj1, 3) + self.assertEqual(obj1 + obj2, 3) + + def test_radd(self): + obj1 = self.lazy_wrap(1) + self.assertEqual(1 + obj1, 2) + def test_trace(self): # See ticket #19456 old_trace_func = sys.gettrace()
# Enhanced Problem Statement: SimpleLazyObject Missing __radd__ Implementation ## Issue Description Django's `SimpleLazyObject` class is missing an implementation of the `__radd__` magic method, which prevents proper reverse addition operations when a lazy object appears on the right side of an addition operation (e.g., `other + lazy_obj`). This is part of a broader limitation where `SimpleLazyObject` lacks several reflection magic methods compared to a complete proxy implementation like `wrapt.ObjectProxy`. The issue occurs because the standard pattern used in `SimpleLazyObject` for creating proxy methods via `new_method_proxy()` doesn't work for reverse operations, as there's no corresponding function in Python's `operator` module (i.e., no `operator.radd`). ## Reproduction Steps ```python from django.utils.functional import SimpleLazyObject # Create a simple lazy object wrapping an integer lazy_five = SimpleLazyObject(lambda: 5) # This works fine - using the implemented __add__ method result1 = lazy_five + 10 # Successfully returns 15 # This fails - missing __radd__ implementation result2 = 10 + lazy_five # TypeError: unsupported operand type(s) for +: 'int' and 'SimpleLazyObject' ``` Internally, when Python evaluates `10 + lazy_five`, it first tries `10.__add__(lazy_five)`, which returns `NotImplemented` because the `int` type doesn't know how to add a `SimpleLazyObject`. Python then looks for `lazy_five.__radd__(10)`, but since this method is not implemented in `SimpleLazyObject`, a `TypeError` is raised. ## Expected Behavior When a `SimpleLazyObject` is used on the right side of an addition operation (or other operators), the operation should succeed by deferring to the wrapped object, just as it does when the lazy object is on the left side. Adding a proper `__radd__` implementation would allow operations like `10 + lazy_five` to work correctly, returning `15` in the example above. ## Exploration Hints ### Files to Examine: - **django/utils/functional.py** - Contains the `SimpleLazyObject` class definition and the `new_method_proxy` function that's used to create proxy methods. This is where the `__radd__` method needs to be added. ### Key Classes/Functions: - **SimpleLazyObject** - A lazy-loading proxy class that delegates method calls to its wrapped object. It implements various magic methods using `new_method_proxy` but is missing `__radd__` and potentially other reflection operators. - **new_method_proxy()** - A function that creates proxy methods for `SimpleLazyObject` which check if the wrapped object is initialized, initialize it if needed, and then delegate the method call to the wrapped object. This approach works for standard operations but not for reverse operations. - **empty** - A sentinel object used to determine if the wrapped object has been initialized. Any fix needs to respect this lazy initialization pattern. ### Areas of Interest: - The pattern for implementing magic methods in `SimpleLazyObject` and how it handles method delegation - Python's method resolution order for binary operations and how it handles reflection methods - The missing reflection operators beyond just `__radd__` that might need similar implementations for completeness ## Fix Hints ### High Confidence Locations: - `django/utils/functional.py` in the `SimpleLazyObject` class definition - The `__radd__` method needs to be added directly to this class, alongside the other magic methods. ### Implementation Hints: ```python def __radd__(self, other): if self._wrapped is empty: self._setup() return other + self._wrapped ``` This implementation follows the pattern used by other methods in `SimpleLazyObject`: check if the wrapped object is initialized, initialize it if needed, then perform the operation with the correct operand order. For completeness, similar implementations should be considered for other reflection operations like `__rsub__`, `__rmul__`, `__rtruediv__`, etc., as they would likely have the same issue. ### Alternative Hypotheses: - The issue might be better addressed with a more comprehensive redesign of how `SimpleLazyObject` handles magic method delegation, potentially using mechanisms similar to those in `wrapt.ObjectProxy` mentioned in the original report. - A more systematic approach using metaclasses or descriptors could automatically handle all magic methods, including reflection operations, without needing to implement each one individually. - The parent class `LazyObject` might be a more appropriate place to implement these methods if the functionality should be shared across multiple lazy object types. - There might be performance considerations for lazy objects that need to be balanced with the completeness of the proxy implementation, especially if adding numerous additional methods.
Could you please give some sample code with your use case? In a boiled-down nutshell: def lazy_consumer(): # something more complex, obviously. return [1, 3, 5] consumer = SimpleLazyObject(lazy_consumer) # inside third party code ... def some_func(param): third_party_code = [...] # then, through parameter passing, my value is provided to be used. # param is at this point, `consumer` third_party_code_plus_mine = third_party_code + param which ultimately yields: TypeError: unsupported operand type(s) for +: 'list' and 'SimpleLazyObject' Seems okay, although I'm not an expert on the SimpleLazyObject class. Replying to kezabelle: def lazy_consumer(): # something more complex, obviously. return [1, 3, 5] consumer = SimpleLazyObject(lazy_consumer) If you know what is the resulting type or possible resulting types of your expression, I think you better use django.utils.functional.lazy which will provide all the necessary methods. Replying to kezabelle: As far as I can tell, the implementation can't just be __radd__ = new_method_proxy(operator.radd) because that doesn't exist, which is rubbish. __radd__ = new_method_proxy(operator.attrgetter("__radd__")) also won't work because types may not have that attr, and attrgetter doesn't supress the exception (correctly) Wouldn't the following code work? __add__ = new_method_proxy(operator.add) __radd__ = new_method_proxy(lambda a, b: operator.add(b, a)) I have tested this and it seems to work as excepted.
2022-02-05T19:34:55Z
4.1
["test_add (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_radd (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)"]
["test_bool (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_bytes (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_class (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_cmp (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_contains (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_copy_class (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_copy_class_no_evaluation (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_copy_list (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_copy_list_no_evaluation (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_deepcopy_class (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_deepcopy_class_no_evaluation (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_deepcopy_list (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_deepcopy_list_no_evaluation (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_delattr (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_delitem (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_dir (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_getattr (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_getitem (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_gt (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_hash (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_iter (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_len (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_lt (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_pickle (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_setattr (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_setattr2 (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_setitem (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_text (utils_tests.test_lazyobject.LazyObjectTestCase)", "test_bool (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_bytes (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_class (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_cmp (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_contains (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_copy_class (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_copy_class_no_evaluation (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_copy_list (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_copy_list_no_evaluation (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_deepcopy_class (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_deepcopy_class_no_evaluation (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_deepcopy_list (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_deepcopy_list_no_evaluation (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_delattr (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_delitem (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_dict (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_dir (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_getattr (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_getitem (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_gt (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_hash (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_iter (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_len (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_list_set (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_lt (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_none (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_pickle (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_repr (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_setattr (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_setattr2 (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_setitem (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_text (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "test_trace (utils_tests.test_lazyobject.SimpleLazyObjectTestCase)", "Test in a fairly synthetic setting."]
647480166bfe7532e8c471fef0146e3a17e6c0c9
django/django
django__django-14667
6a970a8b4600eb91be25f38caed0a52269d6303d
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -2086,7 +2086,12 @@ def add_deferred_loading(self, field_names): self.deferred_loading = existing.union(field_names), True else: # Remove names from the set of any existing "immediate load" names. - self.deferred_loading = existing.difference(field_names), False + if new_existing := existing.difference(field_names): + self.deferred_loading = new_existing, False + else: + self.clear_deferred_loading() + if new_only := set(field_names).difference(existing): + self.deferred_loading = new_only, True def add_immediate_loading(self, field_names): """
diff --git a/tests/defer/tests.py b/tests/defer/tests.py --- a/tests/defer/tests.py +++ b/tests/defer/tests.py @@ -49,8 +49,16 @@ def test_defer_only_chaining(self): qs = Primary.objects.all() self.assert_delayed(qs.only("name", "value").defer("name")[0], 2) self.assert_delayed(qs.defer("name").only("value", "name")[0], 2) + self.assert_delayed(qs.defer('name').only('name').only('value')[0], 2) self.assert_delayed(qs.defer("name").only("value")[0], 2) self.assert_delayed(qs.only("name").defer("value")[0], 2) + self.assert_delayed(qs.only('name').defer('name').defer('value')[0], 1) + self.assert_delayed(qs.only('name').defer('name', 'value')[0], 1) + + def test_defer_only_clear(self): + qs = Primary.objects.all() + self.assert_delayed(qs.only('name').defer('name')[0], 0) + self.assert_delayed(qs.defer('name').only('name')[0], 0) def test_defer_on_an_already_deferred_field(self): qs = Primary.objects.all()
# Enhanced Problem Statement: QuerySet.defer() Not Clearing Deferred Fields When Chaining with only() ## Issue Description When chaining Django ORM's `only()` and `defer()` methods on a QuerySet, there's an unexpected behavior where `defer()` does not properly handle fields that were previously specified in an `only()` call. This results in SQL queries that fetch all model fields instead of excluding the deferred ones as expected. The problem occurs specifically when `defer()` follows `only()` in a method chain. The issue stems from how the `Query` class manages field deferral state internally in the `deferred_loading` attribute, which tracks both the set of fields to load/defer and whether it's an "only" operation (positive list of fields to include) or a "defer" operation (negative list of fields to exclude). When `defer()` is called after `only()`, it fails to properly modify the existing field selection state. ## Reproduction Steps Using a simple model with four fields: ```python class Company(models.Model): name = models.CharField(max_length=100) trade_number = models.CharField(max_length=20) country = models.CharField(max_length=50) # (id field is implicit) ``` Example 1: ```python # This should select only the ID field (since we're only selecting name but then deferring it) queryset = Company.objects.only("name").defer("name") list(queryset) # Evaluate the queryset ``` Generated SQL (incorrect): ```sql SELECT "company"."id", "company"."name", "company"."trade_number", "company"."country" FROM "company" ``` Example 2: ```python # This should also select only the ID field queryset = Company.objects.only("name").defer("name").defer("country") list(queryset) # Evaluate the queryset ``` Generated SQL (incorrect): ```sql SELECT "company"."id", "company"."name", "company"."trade_number", "company"."country" FROM "company" ``` However, the following does work correctly: ```python # This correctly selects only ID and country queryset = Company.objects.only("name", "country").defer("name") list(queryset) # Evaluate the queryset ``` Generated SQL (correct): ```sql SELECT "company"."id", "company"."country" FROM "company" ``` Internally, when `only()` is called, it sets `query.deferred_loading` to a tuple containing a set of field names and `True` (indicating it's an "only" operation). When `defer()` is subsequently called, it's not properly considering the current state and should be removing fields from the "only" set rather than treating it as a separate operation. ## Expected Behavior When chaining `only()` and `defer()` methods, the fields specified in `defer()` should be removed from the set of fields specified in `only()`. For example, `Company.objects.only("name").defer("name")` should result in a query that selects only the `id` field (the primary key is always included unless explicitly deferred): ```sql SELECT "company"."id" FROM "company" ``` Similarly, `Company.objects.only("name", "country").defer("name")` should result in a query that selects only the `id` and `country` fields, which it currently does correctly. ## Exploration Hints ### Files to Examine: - `django/db/models/query.py` - Contains the QuerySet class with `only()` and `defer()` methods that are directly involved in the issue - `django/db/models/sql/query.py` - Contains the Query class that manages the internal representation of SQL queries, including the `deferred_loading` attribute and methods that handle field deferral ### Key Classes/Functions: - `QuerySet.defer()` - Method that adds fields to be deferred but doesn't properly account for previous `only()` calls - `QuerySet.only()` - Method that specifies which fields to include in the query - `Query.add_deferred_loading()` - Likely responsible for managing the deferred fields list in the Query object - `Query.deferred_loading` - Data structure that stores information about deferred fields (a tuple containing a set of field names and a boolean flag) ### Areas of Interest: - The interaction between `only()` and `defer()` methods when chained - How `deferred_loading` is structured and updated when these methods are called - The logic that converts `deferred_loading` into the actual SQL field list - How field deferral state is maintained across method chains in QuerySet ## Fix Hints ### High Confidence Locations: - `QuerySet.defer()` method - Needs to check if `only()` was previously called (by examining `query.deferred_loading`) and handle this case specially - `Query.add_deferred_loading()` - Likely needs to implement proper field set operations between "only" fields and "deferred" fields ### Implementation Hints: - When `defer()` is called after `only()`, it should remove the specified fields from the "only" set rather than treating it as a separate operation - The implementation should handle the case where the same field appears in both `only()` and `defer()` by ensuring it's removed from the final query - Any fix should maintain compatibility with existing behavior where it makes sense (e.g., `defer()` followed by `only()` has a different semantic than `only()` followed by `defer()`) - Consider adding clear documentation about how these methods interact when chained ### Alternative Hypotheses: - The issue might be in how SQL generation interprets the combination of "only" and "deferred" fields, rather than in the QuerySet methods themselves - There could be a more fundamental design issue in how Django tracks field deferral, potentially requiring a more comprehensive refactoring - The problem might relate to how field metadata is cached or tracked across queryset chains, requiring investigation into QuerySet's clone mechanism - The current behavior might be intentional but poorly documented, requiring a review of the intended semantics of these method combinations
Replying to Manuel Baclet: Considering a simple Company model with four fields: id, name, trade_number and country. If we evaluate a queryset containing a .defer() following a .only(), the generated sql query selects unexpected fields. For example: Company.objects.only("name").defer("name") loads all the fields with the following query: SELECT "company"."id", "company"."name", "company"."trade_number", "company"."country" FROM "company" This is an expected behavior, defer() removes fields from the list of fields specified by the only() method (i.e. list of fields that should not be deferred). In this example only() adds name to the list, defer() removes name from the list, so you have empty lists and all fields will be loaded. It is also ​documented: # Final result is that everything except "headline" is deferred. Entry.objects.only("headline", "body").defer("body") Company.objects.only("name").defer("name").defer("country") also loads all the fields with the same query: SELECT "company"."id", "company"."name", "company"."trade_number", "company"."country" FROM "company" I agree you shouldn't get all field, but only pk, name, and trade_number: SELECT "ticket_32704_company"."id", "ticket_32704_company"."name", "ticket_32704_company"."trade_number" FROM "ticket_32704_company" this is due to the fact that defer() doesn't clear the list of deferred field when chaining with only(). I attached a proposed patch. Draft. After reading the documentation carefully, i cannot say that it is clearly stated that deferring all the fields used in a previous .only() call performs a reset of the deferred set. Moreover, in the .defer() ​section, we have: You can make multiple calls to defer(). Each call adds new fields to the deferred set: and this seems to suggest that: calls to .defer() cannot remove items from the deferred set and evaluating qs.defer("some_field") should never fetch the column "some_field" (since this should add "some_field" to the deferred set) the querysets qs.defer("field1").defer("field2") and qs.defer("field1", "field2") should be equivalent IMHO, there is a mismatch between the doc and the actual implementation. calls to .defer() cannot remove items from the deferred set and evaluating qs.defer("some_field") should never fetch the column "some_field" (since this should add "some_field" to the deferred set) Feel-free to propose a docs clarification (see also #24048). the querysets qs.defer("field1").defer("field2") and qs.defer("field1", "field2") should be equivalent That's why I accepted Company.objects.only("name").defer("name").defer("country") as a bug. I think that what is described in the documentation is what users are expected and it is the implementation that should be fixed! With your patch proposal, i do not think that: Company.objects.only("name").defer("name").defer("country") is equivalent to Company.objects.only("name").defer("name", "country") Replying to Manuel Baclet: I think that what is described in the documentation is what users are expected and it is the implementation that should be fixed! I don't agree, and there is no need to shout. As documented: "The only() method is more or less the opposite of defer(). You call it with the fields that should not be deferred ...", so .only('name').defer('name') should return all fields. You can start a discussion on DevelopersMailingList if you don't agree. With your patch proposal, i do not think that: Company.objects.only("name").defer("name").defer("country") is equivalent to Company.objects.only("name").defer("name", "country") Did you check this? with proposed patch country is the only deferred fields in both cases. As far as I'm aware that's an intended behavior. With the proposed patch, I think that: Company.objects.only("name").defer("name", "country") loads all fields whereas: Company.objects.only("name").defer("name").defer("country") loads all fields except "country". Why is that? In the first case: existing.difference(field_names) == {"name"}.difference(["name", "country"]) == empty_set and we go into the if branch clearing all the deferred fields and we are done. In the second case: existing.difference(field_names) == {"name"}.difference(["name"]) == empty_set and we go into the if branch clearing all the deferred fields. Then we add "country" to the set of deferred fields. Hey all, Replying to Mariusz Felisiak: Replying to Manuel Baclet: With your patch proposal, i do not think that: Company.objects.only("name").defer("name").defer("country") is equivalent to Company.objects.only("name").defer("name", "country") Did you check this? with proposed patch country is the only deferred fields in both cases. As far as I'm aware that's an intended behavior. I believe Manuel is right. This happens because the set difference in one direction gives you the empty set that will clear out the deferred fields - but it is missing the fact that we might also be adding more defer fields than we had only fields in the first place, so that we actually switch from an .only() to a .defer() mode. See the corresponding PR that should fix this behaviour ​https://github.com/django/django/pull/14667
2021-07-19T21:08:03Z
4.0
["test_defer_only_chaining (defer.tests.DeferTests)"]
["test_custom_refresh_on_deferred_loading (defer.tests.TestDefer2)", "When an inherited model is fetched from the DB, its PK is also fetched.", "Ensure select_related together with only on a proxy model behaves", "test_eq (defer.tests.TestDefer2)", "test_refresh_not_loading_deferred_fields (defer.tests.TestDefer2)", "test_defer_baseclass_when_subclass_has_added_field (defer.tests.BigChildDeferTests)", "test_defer_subclass (defer.tests.BigChildDeferTests)", "test_defer_subclass_both (defer.tests.BigChildDeferTests)", "test_only_baseclass_when_subclass_has_added_field (defer.tests.BigChildDeferTests)", "test_only_subclass (defer.tests.BigChildDeferTests)", "test_defer (defer.tests.DeferTests)", "test_defer_baseclass_when_subclass_has_no_added_fields (defer.tests.DeferTests)", "test_defer_extra (defer.tests.DeferTests)", "test_defer_foreign_keys_are_deferred_and_not_traversed (defer.tests.DeferTests)", "test_defer_none_to_clear_deferred_set (defer.tests.DeferTests)", "test_defer_of_overridden_scalar (defer.tests.DeferTests)", "test_defer_on_an_already_deferred_field (defer.tests.DeferTests)", "test_defer_only_clear (defer.tests.DeferTests)", "test_defer_select_related_raises_invalid_query (defer.tests.DeferTests)", "test_defer_values_does_not_defer (defer.tests.DeferTests)", "test_defer_with_select_related (defer.tests.DeferTests)", "test_get (defer.tests.DeferTests)", "test_only (defer.tests.DeferTests)", "test_only_baseclass_when_subclass_has_no_added_fields (defer.tests.DeferTests)", "test_only_none_raises_error (defer.tests.DeferTests)", "test_only_select_related_raises_invalid_query (defer.tests.DeferTests)", "test_only_values_does_not_defer (defer.tests.DeferTests)", "test_only_with_select_related (defer.tests.DeferTests)", "test_saving_object_with_deferred_field (defer.tests.DeferTests)"]
475cffd1d64c690cdad16ede4d5e81985738ceb4
django/django
django__django-16046
ec13e801b820614ff374cb0046092caab8d67249
diff --git a/django/utils/numberformat.py b/django/utils/numberformat.py --- a/django/utils/numberformat.py +++ b/django/utils/numberformat.py @@ -25,6 +25,8 @@ def format( module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)). * thousand_sep: Thousand separator symbol (for example ",") """ + if number is None or number == "": + return mark_safe(number) use_grouping = ( use_l10n or (use_l10n is None and settings.USE_L10N) ) and settings.USE_THOUSAND_SEPARATOR
diff --git a/tests/utils_tests/test_numberformat.py b/tests/utils_tests/test_numberformat.py --- a/tests/utils_tests/test_numberformat.py +++ b/tests/utils_tests/test_numberformat.py @@ -172,3 +172,7 @@ def __format__(self, specifier, **kwargs): price = EuroDecimal("1.23") self.assertEqual(nformat(price, ","), "€ 1,23") + + def test_empty(self): + self.assertEqual(nformat("", "."), "") + self.assertEqual(nformat(None, "."), "None")
# Enhanced Problem Statement: NumberFormat String Index Error with Null Values ## Issue Description Django's `numberformat.py` throws an `IndexError: string index out of range` exception when formatting null or empty numeric values in the admin interface's `list_display`. The specific error occurs in the number formatting logic when it attempts to check if a number is negative by accessing the first character of a string representation (`str_number[0] == "-"`), but the string is empty. This issue surfaces in the Django admin when displaying model fields that contain null numeric values. ## Reproduction Steps 1. Create a Django model with a nullable numeric field (IntegerField or FloatField with `null=True`) 2. Include this field in the `list_display` of the corresponding ModelAdmin class 3. Create an instance of the model where this numeric field is null 4. View the model list in the admin interface Internal flow: 1. The admin interface retrieves the model instance with the null field value 2. The value is passed to Django's formatting functions for display in the list view 3. `numberformat.py`'s `format` function tries to check if the value is negative with `str_number[0] == "-"` 4. Since `str_number` is empty (representing a null value), Python raises an IndexError Error stack trace (likely): ``` File ".../django/utils/numberformat.py", line XX, in format if str_number[0] == "-": IndexError: string index out of range ``` ## Expected Behavior The formatting function should check if the string has any characters before attempting to access the first character. When encountering null or empty values, it should handle them gracefully (either by returning an empty string or a placeholder value) instead of raising an exception. ## Exploration Hints ### Files to Examine: - **django/utils/numberformat.py** - Contains the formatting function where the exception is raised when trying to access index 0 of an empty string. This is the primary location of the issue. - **django/contrib/admin/options.py** - Defines the ModelAdmin class that processes field values for display in the admin interface. - **django/contrib/admin/utils.py** - Likely contains the `display_for_field` function that handles formatting different field types. ### Key Classes/Functions: - **numberformat.format()** - The function containing the problematic code that's trying to check for a negative sign without first validating that the string has content. - **display_for_field()** - Determines how different field types are displayed in the admin interface and calls the appropriate formatting functions. - **ModelAdmin.get_list_display()** - Controls which fields are displayed in the admin list view. ### Areas of Interest: - Null value handling in the number formatting pipeline - The conversion from Python values (including None) to string representations before formatting - String validation before character access in formatting functions - How numeric field values are processed differently from other field types ## Fix Hints ### High Confidence Locations: - In `django/utils/numberformat.py`, the `format` function needs validation before accessing `str_number[0]`. This is where the exception occurs. ### Implementation Hints: - Add a guard condition before checking the first character: `if str_number and str_number[0] == "-":` - Alternatively, handle the case more explicitly: ```python if not str_number: return "" # or another appropriate default value if str_number[0] == "-": # existing negative number handling code ``` - The fix should be minimal and focus on defensively checking the string length before indexing. ### Alternative Hypotheses: - The issue might be part of a larger pattern of missing validation in string manipulation functions throughout Django's formatting system. - The error could be related to how empty strings versus None values are handled differently in the admin display pipeline. - There might be an inconsistency in how null values are converted to string representations before reaching the formatting function. - The issue could be exacerbated by certain locale settings or custom formatting options that interact with null values differently.
proposed fix patch Please provide a pull request, including a test.
2022-09-10T13:27:38Z
4.2
["test_empty (utils_tests.test_numberformat.TestNumberFormat)"]
["test_decimal_numbers (utils_tests.test_numberformat.TestNumberFormat)", "test_decimal_subclass (utils_tests.test_numberformat.TestNumberFormat)", "test_float_numbers (utils_tests.test_numberformat.TestNumberFormat)", "test_format_number (utils_tests.test_numberformat.TestNumberFormat)", "test_format_string (utils_tests.test_numberformat.TestNumberFormat)", "test_large_number (utils_tests.test_numberformat.TestNumberFormat)"]
0fbdb9784da915fce5dcc1fe82bac9b4785749e5
django/django
django__django-15790
c627226d05dd52aef59447dcfb29cec2c2b11b8a
diff --git a/django/core/checks/templates.py b/django/core/checks/templates.py --- a/django/core/checks/templates.py +++ b/django/core/checks/templates.py @@ -50,15 +50,15 @@ def check_string_if_invalid_is_string(app_configs, **kwargs): @register(Tags.templates) def check_for_template_tags_with_the_same_name(app_configs, **kwargs): errors = [] - libraries = defaultdict(list) + libraries = defaultdict(set) for conf in settings.TEMPLATES: custom_libraries = conf.get("OPTIONS", {}).get("libraries", {}) for module_name, module_path in custom_libraries.items(): - libraries[module_name].append(module_path) + libraries[module_name].add(module_path) for module_name, module_path in get_template_tag_modules(): - libraries[module_name].append(module_path) + libraries[module_name].add(module_path) for library_name, items in libraries.items(): if len(items) > 1: @@ -66,7 +66,7 @@ def check_for_template_tags_with_the_same_name(app_configs, **kwargs): Error( E003.msg.format( repr(library_name), - ", ".join(repr(item) for item in items), + ", ".join(repr(item) for item in sorted(items)), ), id=E003.id, )
diff --git a/tests/check_framework/test_templates.py b/tests/check_framework/test_templates.py --- a/tests/check_framework/test_templates.py +++ b/tests/check_framework/test_templates.py @@ -158,6 +158,19 @@ def test_template_tags_with_same_library_name(self): [self.error_same_tags], ) + @override_settings( + INSTALLED_APPS=["check_framework.template_test_apps.same_tags_app_1"] + ) + def test_template_tags_same_library_in_installed_apps_libraries(self): + with self.settings( + TEMPLATES=[ + self.get_settings( + "same_tags", "same_tags_app_1.templatetags.same_tags" + ), + ] + ): + self.assertEqual(check_for_template_tags_with_the_same_name(None), []) + @override_settings( INSTALLED_APPS=["check_framework.template_test_apps.same_tags_app_1"] )
# Enhanced Problem Statement: Template Tag Duplicate Detection Bug ## Issue Description There appears to be a bug in Django's `check_for_template_tags_with_the_same_name` system check function that incorrectly identifies a template tag library as a duplicate of itself when the library is specified in `TEMPLATES['OPTIONS']['libraries']`. The system is raising the error `templates.E003` with a message like `'my_tags' is used for multiple template tag modules: 'someapp.templatetags.my_tags', 'someapp.templatetags.my_tags'`, showing the same module path twice. This suggests the system is counting the same template tag module multiple times during validation, rather than correctly identifying that it's the same module. ## Reproduction Steps 1. Create a Django project with a template tag library in an app (e.g., `someapp.templatetags.my_tags`) 2. Add this library to your `TEMPLATES` setting in `settings.py`: ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'libraries': { 'my_tags': 'someapp.templatetags.my_tags', }, }, }, ] ``` 3. Run `python manage.py check` or any Django command that triggers system checks 4. Observe the error: `(templates.E003) 'my_tags' is used for multiple template tag modules: 'someapp.templatetags.my_tags', 'someapp.templatetags.my_tags'` What happens internally: 1. `check_for_template_tags_with_the_same_name` collects template tag libraries from both `TEMPLATES['OPTIONS']['libraries']` and from `get_template_tag_modules()` 2. The same module appears to be added twice to the internal `libraries` dictionary 3. The function detects the duplication and raises the `templates.E003` error, even though it's actually the same module ## Expected Behavior The system check should recognize when the same module path appears multiple times and avoid reporting it as a duplicate of itself. If 'someapp.templatetags.my_tags' is registered through both the `TEMPLATES['OPTIONS']['libraries']` setting and discovered automatically, it should only be counted once in the validation check. ## Exploration Hints ### Files to Examine: - `django/template/checks.py` - Contains the `check_for_template_tags_with_the_same_name` function that's directly responsible for the reported error. This is where the duplicate detection logic needs to be fixed. - `django/template/engine.py` - Handles how Django loads and registers template libraries, including those specified in `TEMPLATES['OPTIONS']['libraries']`. Understanding how libraries are registered here might reveal the root cause. - `django/template/library.py` - Manages template tag libraries and how they're registered with the Django template system. ### Key Classes/Functions: - `check_for_template_tags_with_the_same_name()` - Main function raising the issue. This function collects libraries from two sources (custom libraries in TEMPLATES and modules from get_template_tag_modules) and needs deduplication logic. - `get_template_tag_modules()` - Returns discovered template tag modules that might be overlapping with those explicitly defined in the TEMPLATES setting. - `Engine.get_template_libraries()` - Likely involved in loading and registering the template libraries from settings. ### Areas of Interest: - How template libraries are collected from multiple sources (explicit configuration and autodiscovery) - The data structure used to track library names to module paths (currently a defaultdict(list)) - Logic for detecting genuine duplicate library names vs. the same module referenced multiple times - Error reporting mechanism that shows the same path twice in the error message ## Fix Hints ### High Confidence Locations: - `check_for_template_tags_with_the_same_name()` in `django/template/checks.py` - The issue is likely in how this function collects and deduplicates libraries from multiple sources. The function needs to ensure it doesn't report the same module path as a duplicate of itself. ### Implementation Hints: - Add deduplication logic to avoid adding the same module path twice for the same library name - Consider using a set instead of a list to store module paths for each library name to automatically eliminate duplicates - Modify the collection logic to check if a module path already exists before adding it - Ensure that when comparing module paths, the comparison accounts for possible aliases or import paths that might look different but resolve to the same module ### Alternative Hypotheses: - The issue could be in `get_template_tag_modules()` returning duplicate entries that match those in custom libraries - Multiple TEMPLATES configurations might be causing the same library to be registered multiple times - The error might be correct but the error message formatter could be displaying the module path incorrectly - There could be a caching issue where the same module is loaded twice with different object references but identical paths
Thanks for the report. It's a bug in the new system check (see 004b4620f6f4ad87261e149898940f2dcd5757ef and #32987).
2022-06-23T11:02:06Z
4.2
["test_template_tags_same_library_in_installed_apps_libraries (check_framework.test_templates.CheckTemplateTagLibrariesWithSameName)"]
["Error if template loaders are specified and APP_DIRS is True.", "test_app_dirs_removed (check_framework.test_templates.CheckTemplateSettingsAppDirsTest)", "test_loaders_removed (check_framework.test_templates.CheckTemplateSettingsAppDirsTest)", "test_string_if_invalid_both_are_strings (check_framework.test_templates.CheckTemplateStringIfInvalidTest)", "test_string_if_invalid_first_is_string (check_framework.test_templates.CheckTemplateStringIfInvalidTest)", "test_string_if_invalid_not_specified (check_framework.test_templates.CheckTemplateStringIfInvalidTest)", "test_string_if_invalid_not_string (check_framework.test_templates.CheckTemplateStringIfInvalidTest)", "test_template_tags_with_different_library_name (check_framework.test_templates.CheckTemplateTagLibrariesWithSameName)", "test_template_tags_with_different_name (check_framework.test_templates.CheckTemplateTagLibrariesWithSameName)", "test_template_tags_with_same_library_name (check_framework.test_templates.CheckTemplateTagLibrariesWithSameName)", "test_template_tags_with_same_library_name_and_module_name (check_framework.test_templates.CheckTemplateTagLibrariesWithSameName)", "test_template_tags_with_same_name (check_framework.test_templates.CheckTemplateTagLibrariesWithSameName)"]
0fbdb9784da915fce5dcc1fe82bac9b4785749e5
django/django
django__django-15819
877c800f255ccaa7abde1fb944de45d1616f5cc9
diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py --- a/django/core/management/commands/inspectdb.py +++ b/django/core/management/commands/inspectdb.py @@ -127,12 +127,14 @@ def table2model(table_name): yield "# The error was: %s" % e continue + model_name = table2model(table_name) yield "" yield "" - yield "class %s(models.Model):" % table2model(table_name) - known_models.append(table2model(table_name)) + yield "class %s(models.Model):" % model_name + known_models.append(model_name) used_column_names = [] # Holds column names used in the table so far column_to_field_name = {} # Maps column names to names of model fields + used_relations = set() # Holds foreign relations used in the table. for row in table_description: comment_notes = ( [] @@ -186,6 +188,12 @@ def table2model(table_name): field_type = "%s(%s" % (rel_type, rel_to) else: field_type = "%s('%s'" % (rel_type, rel_to) + if rel_to in used_relations: + extra_params["related_name"] = "%s_%s_set" % ( + model_name.lower(), + att_name, + ) + used_relations.add(rel_to) else: # Calling `get_field_type` to get the field type string and any # additional parameters and notes.
diff --git a/tests/inspectdb/models.py b/tests/inspectdb/models.py --- a/tests/inspectdb/models.py +++ b/tests/inspectdb/models.py @@ -9,6 +9,7 @@ class People(models.Model): class Message(models.Model): from_field = models.ForeignKey(People, models.CASCADE, db_column="from_id") + author = models.ForeignKey(People, models.CASCADE, related_name="message_authors") class PeopleData(models.Model): diff --git a/tests/inspectdb/tests.py b/tests/inspectdb/tests.py --- a/tests/inspectdb/tests.py +++ b/tests/inspectdb/tests.py @@ -433,6 +433,15 @@ def test_introspection_errors(self): # The error message depends on the backend self.assertIn("# The error was:", output) + def test_same_relations(self): + out = StringIO() + call_command("inspectdb", "inspectdb_message", stdout=out) + self.assertIn( + "author = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, " + "related_name='inspectdbmessage_author_set')", + out.getvalue(), + ) + class InspectDBTransactionalTests(TransactionTestCase): available_apps = ["inspectdb"]
# Django inspectdb: Missing related_name for Multiple Foreign Keys to Same Table ## Issue Description Django's `inspectdb` management command generates model code from existing database schemas but fails to add appropriate `related_name` parameters when multiple foreign key fields within the same model reference the same related model. This causes Django's field validation to fail with error E304 when the generated models are used: ``` module.Model.field1: (fields.E304) Reverse accessor for 'module.Model.field1' clashes with reverse accessor for 'module.Model.field2'. HINT: Add or change a related_name argument to the definition for 'module.Model.field1' or 'module.Model.field2'. ``` When Django creates reverse relations automatically, each foreign key field needs a unique reverse accessor name. Without explicit `related_name` parameters, Django creates identical reverse accessors for multiple fields pointing to the same model, causing validation conflicts. ## Reproduction Steps 1. Create a database with a table that has multiple foreign keys to the same table 2. For example, consider a `person` table with both `manager_id` and `assistant_id` columns that are foreign keys to the same `person` table 3. Run Django's inspectdb command: ``` python manage.py inspectdb > models.py ``` 4. The generated models will look something like: ```python class Person(models.Model): name = models.CharField(max_length=100) manager = models.ForeignKey('self', models.DO_NOTHING, db_column='manager_id', blank=True, null=True) assistant = models.ForeignKey('self', models.DO_NOTHING, db_column='assistant_id', blank=True, null=True) ``` 5. When Django validates these models (during startup or migration), it will raise the E304 error because both `manager` and `assistant` fields create the same reverse relation name ## Expected Behavior The `inspectdb` command should detect when multiple fields in the same model reference the same related model and automatically add unique `related_name` parameters to avoid conflicts. The generated model should look like: ```python class Person(models.Model): name = models.CharField(max_length=100) manager = models.ForeignKey('self', models.DO_NOTHING, db_column='manager_id', related_name='manager_set', blank=True, null=True) assistant = models.ForeignKey('self', models.DO_NOTHING, db_column='assistant_id', related_name='assistant_set', blank=True, null=True) ``` The suggested approach is to use the attribute (field) name as the basis for the `related_name` value, which would ensure uniqueness. ## Exploration Hints ### Files to Examine: - `django/core/management/commands/inspectdb.py` - Contains the implementation of the `inspectdb` command that generates model code from database tables. This file needs modification to track multiple references to the same model within a single model. - `django/db/models/fields/related.py` - Contains the `ForeignKey` class implementation, which helps understand how Django handles reverse relations and why the conflict occurs. ### Key Classes/Functions: - `Command.handle_inspection()` - Main method that orchestrates the model generation process. - `Command.get_field_type()` - Determines the field type based on database column information. This is where foreign key fields are identified and generated. - `ForeignKey.__init__()` - Understanding how Django processes `related_name` parameters provides context for implementing the fix. ### Areas of Interest: - The logic that generates field strings for foreign keys needs to be enhanced to track which models have already been referenced within each model being generated. - Special attention should be paid to self-referential foreign keys, as in the case where a model has multiple foreign keys to itself. - The code that builds the field parameter strings needs modification to include `related_name` when appropriate. ## Fix Hints ### High Confidence Locations: - The primary fix should be in `django/core/management/commands/inspectdb.py` in the method that generates foreign key field definitions. - The code needs to track which target models have already been referenced within each model and add a `related_name` parameter when a model is referenced multiple times. ### Implementation Hints: - Maintain a dictionary for each model being processed that tracks which other models it has foreign keys to. - When generating a foreign key field, check if the target model is already in this dictionary. - If it is, add a `related_name` parameter using the field's attribute name (e.g., `related_name='{field_name}_set'`). - Make sure to handle the case of self-referential foreign keys correctly. ### Alternative Hypotheses: - The issue might involve other relation types beyond foreign keys, such as one-to-one fields or many-to-many fields that could cause similar reverse accessor conflicts. - There could be edge cases involving inherited models or abstract base classes that might need special handling. - Instead of automatically generating `related_name` parameters, another approach could be to add comments in the generated code warning about potential conflicts, allowing developers to make explicit decisions about naming. - The database introspection API might not provide sufficient information to reliably detect all cases where `related_name` would be needed, particularly across different database backends.
FIrst solution variant was - ​https://github.com/django/django/pull/15816 But now I see it is not correct. I'll be back with new pull request
2022-07-04T18:29:53Z
4.2
["test_same_relations (inspectdb.tests.InspectDBTestCase)"]
["test_composite_primary_key (inspectdb.tests.InspectDBTransactionalTests)", "inspectdb --include-views creates models for database views.", "test_attribute_name_not_python_keyword (inspectdb.tests.InspectDBTestCase)", "test_char_field_db_collation (inspectdb.tests.InspectDBTestCase)", "Introspection of columns with a custom field (#21090)", "Introspection of column names consist/start with digits (#16536/#17676)", "Test introspection of various Django field types", "test_foreign_key_to_field (inspectdb.tests.InspectDBTestCase)", "Introspection errors should not crash the command, and the error should", "test_json_field (inspectdb.tests.InspectDBTestCase)", "By default the command generates models with `Meta.managed = False`.", "Introspection of column names containing special characters,", "test_stealth_table_name_filter_option (inspectdb.tests.InspectDBTestCase)", "Introspection of table names containing special characters,", "inspectdb can inspect a subset of tables by passing the table names as", "test_table_with_func_unique_constraint (inspectdb.tests.InspectDBTestCase)", "test_text_field_db_collation (inspectdb.tests.InspectDBTestCase)", "test_unique_together_meta (inspectdb.tests.InspectDBTestCase)"]
0fbdb9784da915fce5dcc1fe82bac9b4785749e5
matplotlib/matplotlib
matplotlib__matplotlib-24265
e148998d9bed9d1b53a91587ad48f9bb43c7737f
diff --git a/lib/matplotlib/style/core.py b/lib/matplotlib/style/core.py --- a/lib/matplotlib/style/core.py +++ b/lib/matplotlib/style/core.py @@ -43,6 +43,32 @@ class __getattr__: 'toolbar', 'timezone', 'figure.max_open_warning', 'figure.raise_window', 'savefig.directory', 'tk.window_focus', 'docstring.hardcopy', 'date.epoch'} +_DEPRECATED_SEABORN_STYLES = { + s: s.replace("seaborn", "seaborn-v0_8") + for s in [ + "seaborn", + "seaborn-bright", + "seaborn-colorblind", + "seaborn-dark", + "seaborn-darkgrid", + "seaborn-dark-palette", + "seaborn-deep", + "seaborn-muted", + "seaborn-notebook", + "seaborn-paper", + "seaborn-pastel", + "seaborn-poster", + "seaborn-talk", + "seaborn-ticks", + "seaborn-white", + "seaborn-whitegrid", + ] +} +_DEPRECATED_SEABORN_MSG = ( + "The seaborn styles shipped by Matplotlib are deprecated since %(since)s, " + "as they no longer correspond to the styles shipped by seaborn. However, " + "they will remain available as 'seaborn-v0_8-<style>'. Alternatively, " + "directly use the seaborn API instead.") def _remove_blacklisted_style_params(d, warn=True): @@ -113,31 +139,9 @@ def use(style): def fix_style(s): if isinstance(s, str): s = style_alias.get(s, s) - if s in [ - "seaborn", - "seaborn-bright", - "seaborn-colorblind", - "seaborn-dark", - "seaborn-darkgrid", - "seaborn-dark-palette", - "seaborn-deep", - "seaborn-muted", - "seaborn-notebook", - "seaborn-paper", - "seaborn-pastel", - "seaborn-poster", - "seaborn-talk", - "seaborn-ticks", - "seaborn-white", - "seaborn-whitegrid", - ]: - _api.warn_deprecated( - "3.6", message="The seaborn styles shipped by Matplotlib " - "are deprecated since %(since)s, as they no longer " - "correspond to the styles shipped by seaborn. However, " - "they will remain available as 'seaborn-v0_8-<style>'. " - "Alternatively, directly use the seaborn API instead.") - s = s.replace("seaborn", "seaborn-v0_8") + if s in _DEPRECATED_SEABORN_STYLES: + _api.warn_deprecated("3.6", message=_DEPRECATED_SEABORN_MSG) + s = _DEPRECATED_SEABORN_STYLES[s] return s for style in map(fix_style, styles): @@ -244,17 +248,26 @@ def update_nested_dict(main_dict, new_dict): return main_dict +class _StyleLibrary(dict): + def __getitem__(self, key): + if key in _DEPRECATED_SEABORN_STYLES: + _api.warn_deprecated("3.6", message=_DEPRECATED_SEABORN_MSG) + key = _DEPRECATED_SEABORN_STYLES[key] + + return dict.__getitem__(self, key) + + # Load style library # ================== _base_library = read_style_directory(BASE_LIBRARY_PATH) -library = None +library = _StyleLibrary() available = [] def reload_library(): """Reload the style library.""" - global library - library = update_user_library(_base_library) + library.clear() + library.update(update_user_library(_base_library)) available[:] = sorted(library.keys())
diff --git a/lib/matplotlib/tests/test_style.py b/lib/matplotlib/tests/test_style.py --- a/lib/matplotlib/tests/test_style.py +++ b/lib/matplotlib/tests/test_style.py @@ -184,6 +184,8 @@ def test_deprecated_seaborn_styles(): with pytest.warns(mpl._api.MatplotlibDeprecationWarning): mpl.style.use("seaborn-bright") assert mpl.rcParams == seaborn_bright + with pytest.warns(mpl._api.MatplotlibDeprecationWarning): + mpl.style.library["seaborn-bright"] def test_up_to_date_blacklist():
[Bug]: Setting matplotlib.pyplot.style.library['seaborn-colorblind'] result in key error on matplotlib v3.6.1 ### Bug summary I have code that executes: ``` import matplotlib.pyplot as plt the_rc = plt.style.library["seaborn-colorblind"] ``` Using version 3.4.3 of matplotlib, this works fine. I recently installed my code on a machine with matplotlib version 3.6.1 and upon importing my code, this generated a key error for line `the_rc = plt.style.library["seaborn-colorblind"]` saying "seaborn-colorblind" was a bad key. ### Code for reproduction ```python import matplotlib.pyplot as plt the_rc = plt.style.library["seaborn-colorblind"] ``` ### Actual outcome Traceback (most recent call last): KeyError: 'seaborn-colorblind' ### Expected outcome seaborn-colorblind should be set as the matplotlib library style and I should be able to continue plotting with that style. ### Additional information - Bug occurs with matplotlib version 3.6.1 - Bug does not occur with matplotlib version 3.4.3 - Tested on MacOSX and Ubuntu (same behavior on both) ### Operating system OS/X ### Matplotlib Version 3.6.1 ### Matplotlib Backend MacOSX ### Python version 3.9.7 ### Jupyter version _No response_ ### Installation pip
2022-10-25T02:03:19Z
3.6
["lib/matplotlib/tests/test_style.py::test_deprecated_seaborn_styles"]
["lib/matplotlib/tests/test_style.py::test_invalid_rc_warning_includes_filename", "lib/matplotlib/tests/test_style.py::test_available", "lib/matplotlib/tests/test_style.py::test_use", "lib/matplotlib/tests/test_style.py::test_use_url", "lib/matplotlib/tests/test_style.py::test_single_path", "lib/matplotlib/tests/test_style.py::test_context", "lib/matplotlib/tests/test_style.py::test_context_with_dict", "lib/matplotlib/tests/test_style.py::test_context_with_dict_after_namedstyle", "lib/matplotlib/tests/test_style.py::test_context_with_dict_before_namedstyle", "lib/matplotlib/tests/test_style.py::test_context_with_union_of_dict_and_namedstyle", "lib/matplotlib/tests/test_style.py::test_context_with_badparam", "lib/matplotlib/tests/test_style.py::test_alias[mpl20]", "lib/matplotlib/tests/test_style.py::test_alias[mpl15]", "lib/matplotlib/tests/test_style.py::test_xkcd_no_cm", "lib/matplotlib/tests/test_style.py::test_xkcd_cm", "lib/matplotlib/tests/test_style.py::test_up_to_date_blacklist"]
73909bcb408886a22e2b84581d6b9e6d9907c813
django/django
django__django-16400
0bd2c0c9015b53c41394a1c0989afbfd94dc2830
diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py --- a/django/contrib/auth/management/__init__.py +++ b/django/contrib/auth/management/__init__.py @@ -95,11 +95,16 @@ def create_permissions( .values_list("content_type", "codename") ) - perms = [ - Permission(codename=codename, name=name, content_type=ct) - for ct, (codename, name) in searched_perms - if (ct.pk, codename) not in all_perms - ] + perms = [] + for ct, (codename, name) in searched_perms: + if (ct.pk, codename) not in all_perms: + permission = Permission() + permission._state.db = using + permission.codename = codename + permission.name = name + permission.content_type = ct + perms.append(permission) + Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms:
diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py --- a/tests/auth_tests/test_management.py +++ b/tests/auth_tests/test_management.py @@ -1485,3 +1485,22 @@ def test_permission_with_proxy_content_type_created(self): codename=codename, ).exists() ) + + +class DefaultDBRouter: + """Route all writes to default.""" + + def db_for_write(self, model, **hints): + return "default" + + +@override_settings(DATABASE_ROUTERS=[DefaultDBRouter()]) +class CreatePermissionsMultipleDatabasesTests(TestCase): + databases = {"default", "other"} + + def test_set_permissions_fk_to_using_parameter(self): + Permission.objects.using("other").delete() + with self.assertNumQueries(6, using="other") as captured_queries: + create_permissions(apps.get_app_config("auth"), verbosity=0, using="other") + self.assertIn("INSERT INTO", captured_queries[-1]["sql"].upper()) + self.assertGreater(Permission.objects.using("other").count(), 0)
# Enhanced Problem Statement: Django Migrate Command Doesn't Respect Database Parameter for Permission Creation ## Issue Description When running Django's `migrate` management command with a specific database parameter (`--database=X`), the core migration operations correctly execute against the specified database. However, after the migration completes, a subsequent database read operation that creates or updates Permission objects ignores the database parameter and instead attempts to use the configured database router. This issue specifically affects multi-tenant applications using custom database routers, where a thread-local variable is typically used to determine the current database context. Since management commands don't pass through the HTTP middleware stack, this thread-local state isn't set, causing the database router to fail with an `InvalidTenantException` when it attempts to resolve the database for Permission-related operations. The problem is likely in how Permission objects are created post-migration, where the explicit database parameter provided to the migrate command isn't being properly respected throughout all database operations. ## Reproduction Steps 1. Create a Django project with a custom database router that uses thread-local storage to determine the active database: ```python from threading import local from django.conf import settings local_state = local() class InvalidTenantException(Exception): pass class TenantSubdomainMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): ## Get Subdomain host = request.get_host().split(":")[0] local_state.subdomain = ( # We assume single level of subdomain : app.service.com # HOST_IP : used to for local dev. host if host in settings.HOST_IP else host.split(".")[0] ) response = self.get_response(request) return response class TenantDatabaseRouter: def _default_db(self): subdomain = getattr(local_state, "subdomain", None) if subdomain is not None and subdomain in settings.TENANT_MAP: db_name = settings.TENANT_MAP[local_state.subdomain] return db_name else: raise InvalidTenantException() def db_for_read(self, model, **hints): print("read", hints) return self._default_db() def db_for_write(self, model, **hints): print("write", hints) return self._default_db() def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): return None ``` 2. Configure settings.py with the router: ```python MIDDLEWARE = [ "utils.tenant_db_router.TenantSubdomainMiddleware", "django.middleware.security.SecurityMiddleware", # ... ] TENANT_MAP = {"localhost":"default", "tenant_1":"default"} DATABASE_ROUTERS = ["utils.tenant_db_router.TenantDatabaseRouter"] ``` 3. Run any migration command with a specific database: ```bash python manage.py migrate --database=default ``` 4. Observe the output showing: - "read {}" being printed (indicating a database read operation via the router) - An `InvalidTenantException` being raised because the thread-local variable isn't set Internally, what happens: 1. The migrate command properly uses the specified database for schema migrations 2. After schema migration, Django's permission system attempts to create/update Permission objects 3. During this process, a database read operation is executed without the database context 4. This operation triggers the router's `db_for_read` method without the proper thread-local state 5. The router fails to resolve the database and raises the exception ## Expected Behavior When specifying a database parameter to the migrate command, all database operations—including those for Permission creation—should respect this parameter. The router should not be consulted when an explicit database is provided. Specifically: 1. The migrate command should ensure that all post-migration operations honor the specified database parameter 2. Permission creation should use the specified database directly without falling back to the router 3. No database operations should trigger the router's `db_for_read` or `db_for_write` methods when a specific database is provided to the command ## Exploration Hints ### Files to Examine: - `django/core/management/commands/migrate.py` - Contains the migrate command implementation that processes the database parameter and executes migrations. The issue likely occurs in how this command handles post-migration operations, particularly those related to permissions. - `django/contrib/auth/management/__init__.py` - Contains the `create_permissions` function that is called after migrations to create permission objects for models. This is likely where the database context is lost. - `django/db/migrations/executor.py` - The MigrationExecutor orchestrates the migration process and may be involved in how the database context is maintained or lost during post-migration operations. - `django/contrib/auth/models.py` - Contains the Permission model definition and may include operations that don't properly respect the database parameter. ### Key Classes/Functions: - `create_permissions()` - This function is responsible for creating permissions after migrations and should be passing the database parameter to all database operations. However, it may contain database reads that don't properly respect the database context. - `MigrationExecutor.migrate()` - Coordinates the migration process and may be losing the database context when transitioning to post-migration operations. - `Command.handle()` in `migrate.py` - Processes command-line arguments including the database parameter and should ensure this parameter is respected throughout all operations. - `PermissionManager` class methods - May contain operations that aren't correctly using the provided database parameter. ### Areas of Interest: - The connection between ContentType and Permission creation - Permission objects depend on ContentType objects, and database operations between these models may not be consistently respecting the database parameter. - Post-migration signal handlers and hooks - The issue may be in how these are invoked or how they handle the database context. - Thread-local variable management - Management commands don't go through the middleware pipeline, so thread-local variables aren't set as they would be during HTTP requests. - Database connection handling during different migration phases - The context might be maintained during schema migrations but lost during post-migration operations. ## Fix Hints ### High Confidence Locations: - `create_permissions()` function in `django/contrib/auth/management/__init__.py` - This is likely where the issue occurs, as it handles Permission creation after migrations and may contain database reads that aren't properly respecting the `using` parameter. - `Command.handle()` in `django/core/management/commands/migrate.py` - The way this method invokes post-migration operations might not be correctly passing the database parameter. ### Implementation Hints: 1. Ensure all database operations within `create_permissions()` use the `using` parameter explicitly, especially when fetching ContentTypes or existing Permissions. 2. Check for any implicit database reads that might be happening without a proper database context, such as model `_meta` operations that trigger database lookups. 3. Consider modifying how post-migration hooks are called to ensure they receive and respect the database parameter. 4. Ensure that the connection between ContentType and Permission creation consistently uses the same database throughout all operations. ### Alternative Hypotheses: 1. The issue might be in Django's signal dispatch system, where post_migrate signals aren't properly carrying the database context to their handlers. 2. ContentType operations might be happening separately from Permission operations, with only one respecting the database parameter. 3. The problem could be in how the apps registry is initialized during migrations, potentially causing model operations to use the default database connection. 4. There might be an implicit assumption in Django's permission system that permissions should always be created in the default database, regardless of where the models are migrated. 5. The Django connection handling system might be resetting the connection or connection hints between migration phases, causing later operations to lose context.
Thanks for this report, it's related with adding missing permissions. I was able to fix this by setting _state.db, however I'm not convinced that it's the best solution: django/contrib/auth/management/__init__.py diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index 0b5a982617..27fe0df1d7 100644 a b def create_permissions( 9494 ) 9595 .values_list("content_type", "codename") 9696 ) 97 98 perms = [ 99 Permission(codename=codename, name=name, content_type=ct) 100 for ct, (codename, name) in searched_perms 101 if (ct.pk, codename) not in all_perms 102 ] 97 perms = [] 98 for ct, (codename, name) in searched_perms: 99 if (ct.pk, codename) not in all_perms: 100 permission = Permission() 101 permission._state.db = using 102 permission.codename = codename 103 permission.name = name 104 permission.content_type = ct 105 perms.append(permission) 103106 Permission.objects.using(using).bulk_create(perms) 104107 if verbosity >= 2: 105108 for perm in perms: Partly related to #29843. This patch resolves the problem at my end. I hope it can be added in the 4.1.4 since #29843 seems to be not actively worked on at the moment. After diving a bit deeper it turned out that the issue was with one of the libraries in my project which was not adapted for multi-DB. I've made a PR with changes on the django-admin-interface which resolved my issue. Aryan, this ticket doesn't have submitted PR. Replying to Mariusz Felisiak: Thanks for this report, it's related with adding missing permissions. I was able to fix this by setting _state.db, however I'm not convinced that it's the best solution: django/contrib/auth/management/__init__.py diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index 0b5a982617..27fe0df1d7 100644 a b def create_permissions( 9494 ) 9595 .values_list("content_type", "codename") 9696 ) 97 98 perms = [ 99 Permission(codename=codename, name=name, content_type=ct) 100 for ct, (codename, name) in searched_perms 101 if (ct.pk, codename) not in all_perms 102 ] 97 perms = [] 98 for ct, (codename, name) in searched_perms: 99 if (ct.pk, codename) not in all_perms: 100 permission = Permission() 101 permission._state.db = using 102 permission.codename = codename 103 permission.name = name 104 permission.content_type = ct 105 perms.append(permission) 103106 Permission.objects.using(using).bulk_create(perms) 104107 if verbosity >= 2: 105108 for perm in perms: Partly related to #29843. I think bulk_create already sets the _state.db to the value passed in .using(), right? Or is it in bulk_create that we require _state.db to be set earlier? In which case, we could perhaps change something inside of this method. Replying to Vasanth: After diving a bit deeper it turned out that the issue was with one of the libraries in my project which was not adapted for multi-DB. I've made a PR with changes on the django-admin-interface which resolved my issue. So would it be relevant to close the issue or is the bug really related to Django itself? Replying to David Wobrock: I think bulk_create already sets the _state.db to the value passed in .using(), right? Yes, but it's a different issue, strictly related with Permission and its content_type. get_content_type() is trying to find a content type using obj._state.db so when we create a Permission() without ._state.db it will first try to find a content type in the default db. So would it be relevant to close the issue or is the bug really related to Django itself? IMO we should fix this for permissions. Replying to Mariusz Felisiak: Replying to David Wobrock: I think bulk_create already sets the _state.db to the value passed in .using(), right? Yes, but it's a different issue, strictly related with Permission and its content_type. get_content_type() is trying to find a content type using obj._state.db so when we create a Permission() without ._state.db it will first try to find a content type in the default db. Okay, I understand the issue now, thanks for the details!! First thing, it makes me wonder why we require to have a DB attribute set, at a moment where we are not (yet) interacting with the DB. So we are currently checking, when setting the content_type FK, that the router allows this relation. I guess one option is to not do that for not-saved model instances. Would it make sense to defer this to when we start interacting with the DB? But it brings a whole other lot of changes and challenges, like changing a deep behaviour of FKs and multi-tenancy :/ Apart from that, if we don't want to set directly the internal attribute _state.db, I guess we would need a proper way to pass the db/using to the model instantiation. What would be the most Django-y way? Passing it through the model constructor => this has quite a large impact, as a keyword argument would possibly shadow existing field names: Permission(..., db=using). Quite risky in terms of backward compatibility I guess. Adding a method to Model? Something like: Permission(...).using(db), which could perhaps then be re-used in other places also. (EDIT: which wouldn't work, as the setting the FK happens before setting the DB alias.) What do you think ? :) Or am I missing other solutions? Apart from that, if we don't want to set directly the internal attribute _state.db, I guess we would need a proper way to pass the db/using to the model instantiation. _state is ​documented so using it is not so bad. What would be the most Django-y way? Passing it through the model constructor => this has quite a large impact, as a keyword argument would possibly shadow existing field names: Permission(..., db=using). Quite risky in terms of backward compatibility I guess. Adding a method to Model? Something like: Permission(...).using(db), which could perhaps then be re-used in other places also. What do you think ? :) Or am I missing other solutions? Django doesn't support cross-db relationships and users were always responsible for assigning related objects from the same db. I don't think that we should add more logic to do this. The Permission-content_type issue is really an edge case in managing relations, as for me we don't need a generic solution for it.
2022-12-23T17:17:00Z
4.2
["test_set_permissions_fk_to_using_parameter (auth_tests.test_management.CreatePermissionsMultipleDatabasesTests)"]
["test_actual_implementation (auth_tests.test_management.GetDefaultUsernameTestCase)", "test_existing (auth_tests.test_management.GetDefaultUsernameTestCase)", "test_i18n (auth_tests.test_management.GetDefaultUsernameTestCase)", "test_simple (auth_tests.test_management.GetDefaultUsernameTestCase)", "test_with_database (auth_tests.test_management.GetDefaultUsernameTestCase)", "test_input_not_found (auth_tests.test_management.MockInputTests)", "changepassword --database should operate on the specified DB.", "`post_migrate` handler ordering isn't guaranteed. Simulate a case", "test_default_permissions (auth_tests.test_management.CreatePermissionsTests)", "A proxy model's permissions use its own content type rather than the", "#24075 - Permissions shouldn't be created or deleted if the ContentType", "test_createsuperuser_command_suggested_username_with_database_option (auth_tests.test_management.MultiDBCreatesuperuserTestCase)", "createsuperuser --database should operate on the specified DB.", "test_get_pass (auth_tests.test_management.ChangepasswordManagementCommandTestCase)", "test_get_pass_no_input (auth_tests.test_management.ChangepasswordManagementCommandTestCase)", "test_nonexistent_username (auth_tests.test_management.ChangepasswordManagementCommandTestCase)", "A CommandError should be raised if the user enters in passwords which", "The system username is used if --username isn't provided.", "Executing the changepassword management command should change joe's password", "#21627 -- Executing the changepassword management command should allow", "A CommandError should be thrown by handle() if the user enters in", "Check the operation of the createsuperuser management command", "Creation fails if --username is blank.", "test_blank_username_non_interactive (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "createsuperuser uses a default username when one isn't provided.", "test_email_in_username (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_environment_variable_m2m_non_interactive (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_environment_variable_non_interactive (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "Creation fails if the username already exists.", "Creation fails if the username already exists and a custom user model", "call_command() gets username='janet' and interactive=True.", "test_fields_with_fk (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_fields_with_fk_interactive (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_fields_with_fk_via_option_interactive (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_fields_with_m2m (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_fields_with_m2m_and_through (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_fields_with_m2m_interactive (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_fields_with_m2m_interactive_blank (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_ignore_environment_variable_interactive (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_ignore_environment_variable_non_interactive (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "Creation fails if the username fails validation.", "test_keyboard_interrupt (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_no_email_argument (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_non_ascii_verbose_name (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "You can pass a stdin object as an option and it should be", "Creation should fail if the password fails validation.", "Password validation can be bypassed by entering 'y' at the prompt.", "If the command is not called from a TTY, it should be skipped and a", "A superuser can be created when a custom user model is in use", "A Custom superuser won't be created when a required field isn't provided", "test_swappable_user_username_non_unique (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_usermodel_without_password (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_usermodel_without_password_interactive (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_validate_fk (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_validate_fk_environment_variable (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_validate_fk_via_option_interactive (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_validate_password_against_required_fields (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_validate_password_against_required_fields_via_option (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_validate_password_against_username (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "test_validate_username (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)", "Creation should fail if the user enters blank passwords.", "Creation should fail if the user enters mismatched passwords.", "test_verbosity_zero (auth_tests.test_management.CreatesuperuserManagementCommandTestCase)"]
0fbdb9784da915fce5dcc1fe82bac9b4785749e5
matplotlib/matplotlib
matplotlib__matplotlib-18869
b7d05919865fc0c37a0164cf467d5d5513bd0ede
diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -129,25 +129,60 @@ year = 2007 }""" +# modelled after sys.version_info +_VersionInfo = namedtuple('_VersionInfo', + 'major, minor, micro, releaselevel, serial') -def __getattr__(name): - if name == "__version__": + +def _parse_to_version_info(version_str): + """ + Parse a version string to a namedtuple analogous to sys.version_info. + + See: + https://packaging.pypa.io/en/latest/version.html#packaging.version.parse + https://docs.python.org/3/library/sys.html#sys.version_info + """ + v = parse_version(version_str) + if v.pre is None and v.post is None and v.dev is None: + return _VersionInfo(v.major, v.minor, v.micro, 'final', 0) + elif v.dev is not None: + return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev) + elif v.pre is not None: + releaselevel = { + 'a': 'alpha', + 'b': 'beta', + 'rc': 'candidate'}.get(v.pre[0], 'alpha') + return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1]) + else: + # fallback for v.post: guess-next-dev scheme from setuptools_scm + return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post) + + +def _get_version(): + """Return the version string used for __version__.""" + # Only shell out to a git subprocess if really needed, and not on a + # shallow clone, such as those used by CI, as the latter would trigger + # a warning from setuptools_scm. + root = Path(__file__).resolve().parents[2] + if (root / ".git").exists() and not (root / ".git/shallow").exists(): import setuptools_scm + return setuptools_scm.get_version( + root=root, + version_scheme="post-release", + local_scheme="node-and-date", + fallback_version=_version.version, + ) + else: # Get the version from the _version.py setuptools_scm file. + return _version.version + + +def __getattr__(name): + if name in ("__version__", "__version_info__"): global __version__ # cache it. - # Only shell out to a git subprocess if really needed, and not on a - # shallow clone, such as those used by CI, as the latter would trigger - # a warning from setuptools_scm. - root = Path(__file__).resolve().parents[2] - if (root / ".git").exists() and not (root / ".git/shallow").exists(): - __version__ = setuptools_scm.get_version( - root=root, - version_scheme="post-release", - local_scheme="node-and-date", - fallback_version=_version.version, - ) - else: # Get the version from the _version.py setuptools_scm file. - __version__ = _version.version - return __version__ + __version__ = _get_version() + global __version__info__ # cache it. + __version_info__ = _parse_to_version_info(__version__) + return __version__ if name == "__version__" else __version_info__ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/lib/matplotlib/tests/test_matplotlib.py b/lib/matplotlib/tests/test_matplotlib.py --- a/lib/matplotlib/tests/test_matplotlib.py +++ b/lib/matplotlib/tests/test_matplotlib.py @@ -7,6 +7,16 @@ import matplotlib +@pytest.mark.parametrize('version_str, version_tuple', [ + ('3.5.0', (3, 5, 0, 'final', 0)), + ('3.5.0rc2', (3, 5, 0, 'candidate', 2)), + ('3.5.0.dev820+g6768ef8c4c', (3, 5, 0, 'alpha', 820)), + ('3.5.0.post820+g6768ef8c4c', (3, 5, 1, 'alpha', 820)), +]) +def test_parse_to_version_info(version_str, version_tuple): + assert matplotlib._parse_to_version_info(version_str) == version_tuple + + @pytest.mark.skipif( os.name == "nt", reason="chmod() doesn't work as is on Windows") @pytest.mark.skipif(os.name != "nt" and os.geteuid() == 0,
# Enhanced Problem Statement: Add Comparable Version Info to Matplotlib Top Level ## Issue Description Currently, matplotlib only exposes version information through `__version__` as a string, which makes version comparison cumbersome and potentially error-prone. When using string comparisons for version checks (e.g., comparing '3.10.0' with '3.2.0'), lexicographic ordering would incorrectly evaluate '3.10.0' < '3.2.0' because strings are compared character by character. This becomes problematic as matplotlib's version numbers increase. To improve developer experience and ensure correct version comparisons, matplotlib should expose version information in a more structured format - either as a `version_info` tuple (similar to Python's `sys.version_info`) or as a `LooseVersion` instance that properly handles semantic versioning comparisons. ## Reproduction Steps The current limitation can be demonstrated with: ```python import matplotlib # Attempting to do version comparison with strings if matplotlib.__version__ >= '3.2.0': print("Using newer matplotlib") else: print("Using older matplotlib") # This would incorrectly identify '3.10.0' as older than '3.2.0' # because string comparison compares character by character ``` When matplotlib reaches version 3.10.0 or 4.10.0, these string comparisons will produce incorrect results, requiring users to implement their own version parsing logic. ## Expected Behavior After implementing this feature: 1. Matplotlib should expose either: - A `version_info` tuple (e.g., `(3, 5, 1)` for version 3.5.1) at the top level - A `LooseVersion` instance or similar comparable version object 2. Users should be able to perform semantically correct version comparisons like: ```python import matplotlib if matplotlib.version_info >= (3, 2, 0): print("Using matplotlib 3.2.0 or newer") ``` Or alternatively: ```python import matplotlib if matplotlib.loose_version >= '3.2.0': print("Using matplotlib 3.2.0 or newer") ``` ## Exploration Hints ### Files to Examine: - **lib/matplotlib/__init__.py** - This is the top-level module file where `__version__` is currently defined and where the new version information should be exposed. This file controls what's available in the top-level matplotlib namespace. ### Key Classes/Functions: - **`__version__` variable** - Currently provides version as a string; would need to be parsed to create structured version information. - **`packaging.version.Version` or `distutils.version.LooseVersion`** - Existing libraries that could be leveraged for proper version comparisons (note that `distutils.version` is deprecated in newer Python versions). ### Areas of Interest: - How other Python packages implement version information (e.g., Python's `sys.version_info`, NumPy's `numpy.version.version_info`) - Handling of pre-release versions (alpha, beta, rc) in the version string parsing - Ensuring backward compatibility with existing code that uses `__version__` ## Fix Hints ### High Confidence Locations: - **lib/matplotlib/__init__.py** - The fix should be implemented here, adding new attributes alongside the existing `__version__` string. ### Implementation Hints: 1. **For `version_info` tuple implementation:** ```python # Parse __version__ into a tuple of integers version_parts = __version__.split('.') version_info = tuple(int(v.split('dev')[0].split('+')[0].split('rc')[0]) for v in version_parts) ``` 2. **For `LooseVersion` implementation:** ```python from packaging.version import Version # Modern alternative to distutils.version.LooseVersion loose_version = Version(__version__) ``` 3. **Consider creating a named tuple** for better semantics (similar to `sys.version_info`): ```python from collections import namedtuple VersionInfo = namedtuple('VersionInfo', ['major', 'minor', 'micro']) version_info = VersionInfo(major=int(version_parts[0]), minor=int(version_parts[1]), micro=int(version_parts[2]) if len(version_parts) > 2 else 0) ``` ### Alternative Hypotheses: 1. Instead of adding both options, implement only one (likely `version_info` tuple) as it's more common in Python packages. 2. Consider a property function that lazily creates the version objects only when needed, rather than at import time. 3. The implementation might need to handle additional version components like dev, alpha, beta, or RC versions if matplotlib uses these in its versioning scheme. 4. Rather than adding a new attribute, provide a utility function in the codebase that users can call to get comparable version information.
It seems that `__version_info__` is the way to go. ### Prior art - There's no official specification for version tuples. [PEP 396 - Module Version Numbers](https://www.python.org/dev/peps/pep-0396/) only defines the string `__version__`. - Many projects don't bother with version tuples. - When they do, `__version_info__` seems to be a common thing: - [Stackoverflow discussion](https://stackoverflow.com/a/466694) - [PySide2](https://doc.qt.io/qtforpython-5.12/pysideversion.html#printing-project-and-qt-version) uses it. - Python itself has the string [sys.version](https://docs.python.org/3/library/sys.html#sys.version) and the (named)tuple [sys.version_info](https://docs.python.org/3/library/sys.html#sys.version_info). In analogy to that `__version_info__` next to `__version__` makes sense for packages.
2020-11-01T23:18:42Z
3.3
["lib/matplotlib/tests/test_matplotlib.py::test_parse_to_version_info[3.5.0-version_tuple0]", "lib/matplotlib/tests/test_matplotlib.py::test_parse_to_version_info[3.5.0rc2-version_tuple1]", "lib/matplotlib/tests/test_matplotlib.py::test_parse_to_version_info[3.5.0.dev820+g6768ef8c4c-version_tuple2]", "lib/matplotlib/tests/test_matplotlib.py::test_parse_to_version_info[3.5.0.post820+g6768ef8c4c-version_tuple3]"]
["lib/matplotlib/tests/test_matplotlib.py::test_importable_with_no_home", "lib/matplotlib/tests/test_matplotlib.py::test_use_doc_standard_backends", "lib/matplotlib/tests/test_matplotlib.py::test_importable_with__OO"]
28289122be81e0bc0a6ee0c4c5b7343a46ce2e4e
django/django
django__django-17051
b7a17b0ea0a2061bae752a3a2292007d41825814
diff --git a/django/db/models/query.py b/django/db/models/query.py --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1837,12 +1837,17 @@ def _batched_insert( inserted_rows = [] bulk_return = connection.features.can_return_rows_from_bulk_insert for item in [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]: - if bulk_return and on_conflict is None: + if bulk_return and ( + on_conflict is None or on_conflict == OnConflict.UPDATE + ): inserted_rows.extend( self._insert( item, fields=fields, using=self.db, + on_conflict=on_conflict, + update_fields=update_fields, + unique_fields=unique_fields, returning_fields=self.model._meta.db_returning_fields, ) )
diff --git a/tests/bulk_create/tests.py b/tests/bulk_create/tests.py --- a/tests/bulk_create/tests.py +++ b/tests/bulk_create/tests.py @@ -582,12 +582,16 @@ def _test_update_conflicts_two_fields(self, unique_fields): TwoFields(f1=1, f2=1, name="c"), TwoFields(f1=2, f2=2, name="d"), ] - TwoFields.objects.bulk_create( + results = TwoFields.objects.bulk_create( conflicting_objects, update_conflicts=True, unique_fields=unique_fields, update_fields=["name"], ) + self.assertEqual(len(results), len(conflicting_objects)) + if connection.features.can_return_rows_from_bulk_insert: + for instance in results: + self.assertIsNotNone(instance.pk) self.assertEqual(TwoFields.objects.count(), 2) self.assertCountEqual( TwoFields.objects.values("f1", "f2", "name"), @@ -619,7 +623,6 @@ def test_update_conflicts_unique_fields_pk(self): TwoFields(f1=2, f2=2, name="b"), ] ) - self.assertEqual(TwoFields.objects.count(), 2) obj1 = TwoFields.objects.get(f1=1) obj2 = TwoFields.objects.get(f1=2) @@ -627,12 +630,16 @@ def test_update_conflicts_unique_fields_pk(self): TwoFields(pk=obj1.pk, f1=3, f2=3, name="c"), TwoFields(pk=obj2.pk, f1=4, f2=4, name="d"), ] - TwoFields.objects.bulk_create( + results = TwoFields.objects.bulk_create( conflicting_objects, update_conflicts=True, unique_fields=["pk"], update_fields=["name"], ) + self.assertEqual(len(results), len(conflicting_objects)) + if connection.features.can_return_rows_from_bulk_insert: + for instance in results: + self.assertIsNotNone(instance.pk) self.assertEqual(TwoFields.objects.count(), 2) self.assertCountEqual( TwoFields.objects.values("f1", "f2", "name"), @@ -680,12 +687,16 @@ def _test_update_conflicts_unique_two_fields(self, unique_fields): description=("Japan is an island country in East Asia."), ), ] - Country.objects.bulk_create( + results = Country.objects.bulk_create( new_data, update_conflicts=True, update_fields=["description"], unique_fields=unique_fields, ) + self.assertEqual(len(results), len(new_data)) + if connection.features.can_return_rows_from_bulk_insert: + for instance in results: + self.assertIsNotNone(instance.pk) self.assertEqual(Country.objects.count(), 6) self.assertCountEqual( Country.objects.values("iso_two_letter", "description"), @@ -743,12 +754,16 @@ def _test_update_conflicts(self, unique_fields): UpsertConflict(number=2, rank=2, name="Olivia"), UpsertConflict(number=3, rank=1, name="Hannah"), ] - UpsertConflict.objects.bulk_create( + results = UpsertConflict.objects.bulk_create( conflicting_objects, update_conflicts=True, update_fields=["name", "rank"], unique_fields=unique_fields, ) + self.assertEqual(len(results), len(conflicting_objects)) + if connection.features.can_return_rows_from_bulk_insert: + for instance in results: + self.assertIsNotNone(instance.pk) self.assertEqual(UpsertConflict.objects.count(), 3) self.assertCountEqual( UpsertConflict.objects.values("number", "rank", "name"), @@ -759,12 +774,16 @@ def _test_update_conflicts(self, unique_fields): ], ) - UpsertConflict.objects.bulk_create( + results = UpsertConflict.objects.bulk_create( conflicting_objects + [UpsertConflict(number=4, rank=4, name="Mark")], update_conflicts=True, update_fields=["name", "rank"], unique_fields=unique_fields, ) + self.assertEqual(len(results), 4) + if connection.features.can_return_rows_from_bulk_insert: + for instance in results: + self.assertIsNotNone(instance.pk) self.assertEqual(UpsertConflict.objects.count(), 4) self.assertCountEqual( UpsertConflict.objects.values("number", "rank", "name"), @@ -803,12 +822,16 @@ def test_update_conflicts_unique_fields_update_fields_db_column(self): FieldsWithDbColumns(rank=1, name="c"), FieldsWithDbColumns(rank=2, name="d"), ] - FieldsWithDbColumns.objects.bulk_create( + results = FieldsWithDbColumns.objects.bulk_create( conflicting_objects, update_conflicts=True, unique_fields=["rank"], update_fields=["name"], ) + self.assertEqual(len(results), len(conflicting_objects)) + if connection.features.can_return_rows_from_bulk_insert: + for instance in results: + self.assertIsNotNone(instance.pk) self.assertEqual(FieldsWithDbColumns.objects.count(), 2) self.assertCountEqual( FieldsWithDbColumns.objects.values("rank", "name"),
# Enhanced Problem Statement: QuerySet.bulk_create() Not Returning IDs with update_conflicts=True ## Issue Description When using `bulk_create()` with `update_conflicts=True`, Django does not populate the primary key IDs in the returned objects, even though PostgreSQL is capable of returning these IDs. Currently, the IDs are not returned regardless of which conflict handling strategy is used (`ignore_conflicts=True` or `update_conflicts=True`). While there's a valid reason for this behavior with `ignore_conflicts=True` (PostgreSQL doesn't return IDs for ignored rows), there's no technical limitation preventing Django from returning IDs when using `update_conflicts=True`. The issue stems from how Django constructs SQL queries - it's removing the `RETURNING id` clause from the query when any conflict handling is enabled, rather than distinguishing between the two conflict handling modes. ## Reproduction Steps ```python # Create a model instance with a potential conflict obj = MyModel(id=1, field1="value", field2="value") obj.save() # Try to bulk create objects with update_conflicts=True objects = [ MyModel(id=1, field1="new_value", field2="new_value"), # Will conflict and update MyModel(field1="value2", field2="value2") # New object ] created_objects = MyModel.objects.bulk_create( objects, update_conflicts=True, update_fields=["field1", "field2"], unique_fields=["id"] ) # The created_objects will have: # - First object: id=None (despite being updated successfully) # - Second object: id=None (despite being created with a new ID) # The resulting SQL lacks the RETURNING clause: # INSERT INTO "my_model" (...) # VALUES (...) # ON CONFLICT(...) DO UPDATE SET ... # # If manually modified to include RETURNING: # INSERT INTO "my_model" (...) # VALUES (...) # ON CONFLICT(...) DO UPDATE SET ... # RETURNING my_model.id # # PostgreSQL would correctly return the IDs ``` ## Expected Behavior Django should include the `RETURNING id` clause in the SQL query when `update_conflicts=True` is specified, allowing the primary keys of all objects (both created and updated) to be populated in the returned objects. The current behavior for `ignore_conflicts=True` should remain unchanged as PostgreSQL can't reliably return IDs for ignored rows. ## Exploration Hints ### Files to Examine: - `django/db/models/query.py` - Contains the `QuerySet` class with the `bulk_create()` method and the underlying `_insert()` method, which is the central location where the issue occurs. The file implements the logic for handling conflict resolution options in bulk operations. - `django/db/backends/postgresql/operations.py` - Contains PostgreSQL-specific SQL generation for operations, which may influence how RETURNING clauses are handled in this database backend. - `django/db/backends/base/operations.py` - Defines the base interface for database operations across Django ORM, which might contain relevant methods for generating SQL for bulk inserts. ### Key Classes/Functions: - `QuerySet.bulk_create()` - The primary method users interact with, which delegates to internal methods for batching and insertion. - `QuerySet._batched_insert()` - Handles batching of inserts and passes parameters to `_insert()`. - `QuerySet._insert()` - The critical method where the issue occurs. This is where `returning_fields` gets removed when conflict handling is enabled. - `BaseDatabaseOperations.bulk_insert_sql()` - Likely involved in generating the SQL for bulk operations, particularly how RETURNING clauses are included. ### Areas of Interest: - The logic that determines when to include `returning_fields` in the SQL query is the key focus. The bug report mentions finding where `returning_fields` gets removed in the Django source. - The conditional check that removes `returning_fields` likely doesn't differentiate between `ignore_conflicts` and `update_conflicts`. - Code that constructs SQL queries with `ON CONFLICT` clauses and determines whether to include the `RETURNING` part. - How Django processes returned IDs and assigns them to the model instances in memory. ## Fix Hints ### High Confidence Locations: - The most likely location for the fix is in the `QuerySet._insert()` method where there's likely a condition that removes `returning_fields` when any conflict handling is enabled. This condition needs to be modified to only remove `returning_fields` when `ignore_conflicts=True` but preserve them when `update_conflicts=True`. ### Implementation Hints: - Modify the condition in `_insert()` that removes `returning_fields` to check specifically for `ignore_conflicts` rather than any conflict handling. - Ensure the fix differentiates between the two conflict handling strategies, only excluding `returning_fields` for `ignore_conflicts`. - The change should be minimal - likely just modifying a conditional check - while maintaining the existing behavior for `ignore_conflicts=True`. - Update documentation to clarify that primary keys will now be set when using `update_conflicts=True`. ### Alternative Hypotheses: 1. There might be database backend compatibility issues with other databases that would need to be considered - the fix might need to be PostgreSQL-specific. 2. There could be performance implications to requesting returned IDs with conflict updates that should be evaluated before implementation. 3. The current behavior might have been intentional to maintain consistency between different conflict handling strategies, so the change might require broader API considerations. 4. The issue might involve multiple files in the query generation process, requiring more complex changes to how bulk operations are handled. 5. Some databases might not support returning IDs with conflict updates, so Django might be using a least-common-denominator approach that needs to be made more database-specific.
Thanks for the ticket. I've checked and it works on PostgreSQL, MariaDB 10.5+, and SQLite 3.35+: django/db/models/query.py diff --git a/django/db/models/query.py b/django/db/models/query.py index a5b0f464a9..f1e052cb36 100644 a b class QuerySet(AltersData): 18371837 inserted_rows = [] 18381838 bulk_return = connection.features.can_return_rows_from_bulk_insert 18391839 for item in [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]: 1840 if bulk_return and on_conflict is None: 1840 if bulk_return and (on_conflict is None or on_conflict == OnConflict.UPDATE): 18411841 inserted_rows.extend( 18421842 self._insert( 18431843 item, 18441844 fields=fields, 18451845 using=self.db, 1846 on_conflict=on_conflict, 1847 update_fields=update_fields, 1848 unique_fields=unique_fields, 18461849 returning_fields=self.model._meta.db_returning_fields, 18471850 ) 18481851 ) Would you like to prepare a patch via GitHub PR? (docs changes and tests are required) Sure I will. Replying to Thomas C: Sure I will. Thanks. About tests, it should be enough to add some assertions to existing tests: _test_update_conflicts_two_fields(), test_update_conflicts_unique_fields_pk(), _test_update_conflicts_unique_two_fields(), _test_update_conflicts(), and test_update_conflicts_unique_fields_update_fields_db_column() when connection.features.can_return_rows_from_bulk_insert is True. See ​https://github.com/django/django/pull/17051
2023-07-07T11:01:09Z
5.0
["test_update_conflicts_two_fields_unique_fields_first (bulk_create.tests.BulkCreateTests.test_update_conflicts_two_fields_unique_fields_first)", "test_update_conflicts_two_fields_unique_fields_second (bulk_create.tests.BulkCreateTests.test_update_conflicts_two_fields_unique_fields_second)", "test_update_conflicts_unique_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_fields)", "test_update_conflicts_unique_fields_update_fields_db_column (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_fields_update_fields_db_column)", "test_update_conflicts_unique_two_fields_unique_fields_both (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_two_fields_unique_fields_both)"]
["test_batch_same_vals (bulk_create.tests.BulkCreateTests.test_batch_same_vals)", "test_bulk_insert_expressions (bulk_create.tests.BulkCreateTests.test_bulk_insert_expressions)", "test_bulk_insert_now (bulk_create.tests.BulkCreateTests.test_bulk_insert_now)", "test_bulk_insert_nullable_fields (bulk_create.tests.BulkCreateTests.test_bulk_insert_nullable_fields)", "test_efficiency (bulk_create.tests.BulkCreateTests.test_efficiency)", "test_empty_model (bulk_create.tests.BulkCreateTests.test_empty_model)", "test_explicit_batch_size (bulk_create.tests.BulkCreateTests.test_explicit_batch_size)", "test_explicit_batch_size_efficiency (bulk_create.tests.BulkCreateTests.test_explicit_batch_size_efficiency)", "test_explicit_batch_size_respects_max_batch_size (bulk_create.tests.BulkCreateTests.test_explicit_batch_size_respects_max_batch_size)", "test_ignore_conflicts_ignore (bulk_create.tests.BulkCreateTests.test_ignore_conflicts_ignore)", "test_ignore_update_conflicts_exclusive (bulk_create.tests.BulkCreateTests.test_ignore_update_conflicts_exclusive)", "test_invalid_batch_size_exception (bulk_create.tests.BulkCreateTests.test_invalid_batch_size_exception)", "test_large_batch (bulk_create.tests.BulkCreateTests.test_large_batch)", "test_large_batch_efficiency (bulk_create.tests.BulkCreateTests.test_large_batch_efficiency)", "Test inserting a large batch with objects having primary key set", "test_large_single_field_batch (bulk_create.tests.BulkCreateTests.test_large_single_field_batch)", "test_long_and_short_text (bulk_create.tests.BulkCreateTests.test_long_and_short_text)", "Inserting non-ASCII values with a length in the range 2001 to 4000", "test_multi_table_inheritance_unsupported (bulk_create.tests.BulkCreateTests.test_multi_table_inheritance_unsupported)", "test_non_auto_increment_pk (bulk_create.tests.BulkCreateTests.test_non_auto_increment_pk)", "test_non_auto_increment_pk_efficiency (bulk_create.tests.BulkCreateTests.test_non_auto_increment_pk_efficiency)", "test_nullable_fk_after_parent (bulk_create.tests.BulkCreateTests.test_nullable_fk_after_parent)", "test_nullable_fk_after_parent_bulk_create (bulk_create.tests.BulkCreateTests.test_nullable_fk_after_parent_bulk_create)", "test_proxy_inheritance_supported (bulk_create.tests.BulkCreateTests.test_proxy_inheritance_supported)", "test_set_pk_and_insert_single_item (bulk_create.tests.BulkCreateTests.test_set_pk_and_insert_single_item)", "test_set_pk_and_query_efficiency (bulk_create.tests.BulkCreateTests.test_set_pk_and_query_efficiency)", "test_set_state (bulk_create.tests.BulkCreateTests.test_set_state)", "test_set_state_with_pk_specified (bulk_create.tests.BulkCreateTests.test_set_state_with_pk_specified)", "test_simple (bulk_create.tests.BulkCreateTests.test_simple)", "test_unsaved_parent (bulk_create.tests.BulkCreateTests.test_unsaved_parent)", "test_update_conflicts_invalid_unique_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_invalid_unique_fields)", "test_update_conflicts_invalid_update_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_invalid_update_fields)", "test_update_conflicts_no_update_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_no_update_fields)", "test_update_conflicts_nonexistent_update_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_nonexistent_update_fields)", "test_update_conflicts_pk_in_update_fields (bulk_create.tests.BulkCreateTests.test_update_conflicts_pk_in_update_fields)", "test_update_conflicts_two_fields_unique_fields_both (bulk_create.tests.BulkCreateTests.test_update_conflicts_two_fields_unique_fields_both)", "test_update_conflicts_unique_fields_pk (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_fields_pk)", "test_update_conflicts_unique_fields_required (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_fields_required)", "test_update_conflicts_unique_two_fields_unique_fields_one (bulk_create.tests.BulkCreateTests.test_update_conflicts_unique_two_fields_unique_fields_one)"]
4a72da71001f154ea60906a2f74898d32b7322a7
django/django
django__django-16910
4142739af1cda53581af4169dbe16d6cd5e26948
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -779,7 +779,13 @@ def _get_only_select_mask(self, opts, mask, select_mask=None): # Only include fields mentioned in the mask. for field_name, field_mask in mask.items(): field = opts.get_field(field_name) - field_select_mask = select_mask.setdefault(field, {}) + # Retrieve the actual field associated with reverse relationships + # as that's what is expected in the select mask. + if field in opts.related_objects: + field_key = field.field + else: + field_key = field + field_select_mask = select_mask.setdefault(field_key, {}) if field_mask: if not field.is_relation: raise FieldError(next(iter(field_mask)))
diff --git a/tests/defer_regress/tests.py b/tests/defer_regress/tests.py --- a/tests/defer_regress/tests.py +++ b/tests/defer_regress/tests.py @@ -178,6 +178,16 @@ def test_reverse_one_to_one_relations(self): self.assertEqual(i.one_to_one_item.name, "second") with self.assertNumQueries(1): self.assertEqual(i.value, 42) + with self.assertNumQueries(1): + i = Item.objects.select_related("one_to_one_item").only( + "name", "one_to_one_item__item" + )[0] + self.assertEqual(i.one_to_one_item.pk, o2o.pk) + self.assertEqual(i.name, "first") + with self.assertNumQueries(1): + self.assertEqual(i.one_to_one_item.name, "second") + with self.assertNumQueries(1): + self.assertEqual(i.value, 42) def test_defer_with_select_related(self): item1 = Item.objects.create(name="first", value=47) @@ -277,6 +287,28 @@ def test_defer_many_to_many_ignored(self): with self.assertNumQueries(1): self.assertEqual(Request.objects.defer("items").get(), request) + def test_only_many_to_many_ignored(self): + location = Location.objects.create() + request = Request.objects.create(location=location) + with self.assertNumQueries(1): + self.assertEqual(Request.objects.only("items").get(), request) + + def test_defer_reverse_many_to_many_ignored(self): + location = Location.objects.create() + request = Request.objects.create(location=location) + item = Item.objects.create(value=1) + request.items.add(item) + with self.assertNumQueries(1): + self.assertEqual(Item.objects.defer("request").get(), item) + + def test_only_reverse_many_to_many_ignored(self): + location = Location.objects.create() + request = Request.objects.create(location=location) + item = Item.objects.create(value=1) + request.items.add(item) + with self.assertNumQueries(1): + self.assertEqual(Item.objects.only("request").get(), item) + class DeferDeletionSignalsTests(TestCase): senders = [Item, Proxy] diff --git a/tests/select_related_onetoone/tests.py b/tests/select_related_onetoone/tests.py --- a/tests/select_related_onetoone/tests.py +++ b/tests/select_related_onetoone/tests.py @@ -249,6 +249,9 @@ def test_inheritance_deferred2(self): self.assertEqual(p.child1.name2, "n2") p = qs.get(name2="n2") with self.assertNumQueries(0): + self.assertEqual(p.child1.value, 1) + self.assertEqual(p.child1.child4.value4, 4) + with self.assertNumQueries(2): self.assertEqual(p.child1.name1, "n1") self.assertEqual(p.child1.child4.name1, "n1")
QuerySet.only() doesn't work with select_related() on a reverse OneToOneField relation. Description On Django 4.2 calling only() with select_related() on a query using the reverse lookup for a OneToOne relation does not generate the correct query. All the fields from the related model are still included in the generated SQL. Sample models: class Main(models.Model): main_field_1 = models.CharField(blank=True, max_length=45) main_field_2 = models.CharField(blank=True, max_length=45) main_field_3 = models.CharField(blank=True, max_length=45) class Secondary(models.Model): main = models.OneToOneField(Main, primary_key=True, related_name='secondary', on_delete=models.CASCADE) secondary_field_1 = models.CharField(blank=True, max_length=45) secondary_field_2 = models.CharField(blank=True, max_length=45) secondary_field_3 = models.CharField(blank=True, max_length=45) Sample code: Main.objects.select_related('secondary').only('main_field_1', 'secondary__secondary_field_1') Generated query on Django 4.2.1: SELECT "bugtest_main"."id", "bugtest_main"."main_field_1", "bugtest_secondary"."main_id", "bugtest_secondary"."secondary_field_1", "bugtest_secondary"."secondary_field_2", "bugtest_secondary"."secondary_field_3" FROM "bugtest_main" LEFT OUTER JOIN "bugtest_secondary" ON ("bugtest_main"."id" = "bugtest_secondary"."main_id") Generated query on Django 4.1.9: SELECT "bugtest_main"."id", "bugtest_main"."main_field_1", "bugtest_secondary"."main_id", "bugtest_secondary"."secondary_field_1" FROM "bugtest_main" LEFT OUTER JOIN "bugtest_secondary" ON ("bugtest_main"."id" = "bugtest_secondary"."main_id")
Thanks for the report! Regression in b3db6c8dcb5145f7d45eff517bcd96460475c879. Reproduced at 881cc139e2d53cc1d3ccea7f38faa960f9e56597.
2023-05-31T22:28:10Z
5.0
["test_inheritance_deferred2 (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_inheritance_deferred2)", "test_reverse_one_to_one_relations (defer_regress.tests.DeferRegressionTest.test_reverse_one_to_one_relations)"]
["test_reverse_related_validation (select_related_onetoone.tests.ReverseSelectRelatedValidationTests.test_reverse_related_validation)", "test_reverse_related_validation_with_filtered_relation (select_related_onetoone.tests.ReverseSelectRelatedValidationTests.test_reverse_related_validation_with_filtered_relation)", "test_delete_defered_model (defer_regress.tests.DeferDeletionSignalsTests.test_delete_defered_model)", "test_delete_defered_proxy_model (defer_regress.tests.DeferDeletionSignalsTests.test_delete_defered_proxy_model)", "test_back_and_forward (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_back_and_forward)", "test_basic (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_basic)", "test_follow_from_child_class (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_follow_from_child_class)", "test_follow_inheritance (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_follow_inheritance)", "test_follow_next_level (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_follow_next_level)", "test_follow_two (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_follow_two)", "test_follow_two_next_level (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_follow_two_next_level)", "test_forward_and_back (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_forward_and_back)", "test_inheritance_deferred (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_inheritance_deferred)", "Ticket #13839: select_related() should NOT cache None", "test_multiinheritance_two_subclasses (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_multiinheritance_two_subclasses)", "test_multiple_subclass (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_multiple_subclass)", "test_not_followed_by_default (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_not_followed_by_default)", "test_nullable_relation (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_nullable_relation)", "test_onetoone_with_subclass (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_onetoone_with_subclass)", "test_onetoone_with_two_subclasses (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_onetoone_with_two_subclasses)", "test_parent_only (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_parent_only)", "test_self_relation (select_related_onetoone.tests.ReverseSelectRelatedTestCase.test_self_relation)", "test_basic (defer_regress.tests.DeferRegressionTest.test_basic)", "test_common_model_different_mask (defer_regress.tests.DeferRegressionTest.test_common_model_different_mask)", "test_defer_annotate_select_related (defer_regress.tests.DeferRegressionTest.test_defer_annotate_select_related)", "test_defer_many_to_many_ignored (defer_regress.tests.DeferRegressionTest.test_defer_many_to_many_ignored)", "test_defer_reverse_many_to_many_ignored (defer_regress.tests.DeferRegressionTest.test_defer_reverse_many_to_many_ignored)", "test_defer_with_select_related (defer_regress.tests.DeferRegressionTest.test_defer_with_select_related)", "test_only_and_defer_usage_on_proxy_models (defer_regress.tests.DeferRegressionTest.test_only_and_defer_usage_on_proxy_models)", "test_only_many_to_many_ignored (defer_regress.tests.DeferRegressionTest.test_only_many_to_many_ignored)", "test_only_reverse_many_to_many_ignored (defer_regress.tests.DeferRegressionTest.test_only_reverse_many_to_many_ignored)", "test_only_with_select_related (defer_regress.tests.DeferRegressionTest.test_only_with_select_related)", "test_proxy_model_defer_with_select_related (defer_regress.tests.DeferRegressionTest.test_proxy_model_defer_with_select_related)", "test_resolve_columns (defer_regress.tests.DeferRegressionTest.test_resolve_columns)", "test_ticket_16409 (defer_regress.tests.DeferRegressionTest.test_ticket_16409)", "test_ticket_23270 (defer_regress.tests.DeferRegressionTest.test_ticket_23270)"]
4a72da71001f154ea60906a2f74898d32b7322a7
matplotlib/matplotlib
matplotlib__matplotlib-23314
97fc1154992f64cfb2f86321155a7404efeb2d8a
diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -387,6 +387,8 @@ def apply_aspect(self, position=None): @martist.allow_rasterization def draw(self, renderer): + if not self.get_visible(): + return self._unstale_viewLim() # draw the background patch
diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -45,6 +45,12 @@ # the tests with multiple threads. +@check_figures_equal(extensions=["png"]) +def test_invisible_axes(fig_test, fig_ref): + ax = fig_test.subplots() + ax.set_visible(False) + + def test_get_labels(): fig, ax = plt.subplots() ax.set_xlabel('x label') @@ -7319,7 +7325,7 @@ def test_redraw_in_frame(): ax.redraw_in_frame() -def test_invisible_axes(): +def test_invisible_axes_events(): # invisible axes should not respond to events... fig, ax = plt.subplots() assert fig.canvas.inaxes((200, 200)) is not None diff --git a/lib/mpl_toolkits/tests/test_mplot3d.py b/lib/mpl_toolkits/tests/test_mplot3d.py --- a/lib/mpl_toolkits/tests/test_mplot3d.py +++ b/lib/mpl_toolkits/tests/test_mplot3d.py @@ -21,6 +21,12 @@ image_comparison, remove_text=True, style='default') +@check_figures_equal(extensions=["png"]) +def test_invisible_axes(fig_test, fig_ref): + ax = fig_test.subplots(subplot_kw=dict(projection='3d')) + ax.set_visible(False) + + def test_aspect_equal_error(): fig = plt.figure() ax = fig.add_subplot(projection='3d')
# Enhanced Problem Statement: `set_visible()` Not Working for 3D Projection in Matplotlib ## Issue Description When using `set_visible(False)` on a subplot with `projection="3d"` in Matplotlib, the 3D subplot remains visible, contrary to expected behavior. This issue occurs because the `Axes3D` class in mplot3d does not properly implement or honor the visibility setting inherited from the parent `Artist` class. While the visibility flag is correctly set at the Artist level, the custom rendering pipeline for 3D axes appears to bypass or ignore this visibility check, causing 3D subplots to remain visible even when explicitly set to be hidden. ## Reproduction Steps ```python import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw={'projection': '3d'}) ax1.scatter(1,1,1) ax2.scatter(1,1,1, c='r') ax1.set_visible(False) plt.show() ``` Internally, what happens: 1. The `set_visible(False)` call on `ax1` correctly sets the `_visible` attribute to `False` on the Axes3D object 2. However, when rendering occurs, the `draw()` method in Axes3D does not check this visibility flag before rendering its components 3. All 3D-specific elements (panes, grids, axis lines) continue to be rendered regardless of the visibility setting 4. This creates a discrepancy between 2D axes (where visibility works as expected) and 3D axes ## Expected Behavior When `set_visible(False)` is called on a 3D subplot, the entire subplot should become invisible, just as it does for regular 2D subplots. None of the 3D subplot elements should be rendered on the figure. ## Exploration Hints ### Files to Examine: - **lib/mpl_toolkits/mplot3d/axes3d.py** - This is the primary file implementing 3D axes functionality. It contains the `Axes3D` class which handles the rendering of 3D projections but likely doesn't properly respect visibility settings. - **lib/matplotlib/artist.py** - Contains the base `Artist` class which implements the core `set_visible()` method that all matplotlib visual elements inherit. The visibility mechanism defined here is not being properly honored in 3D contexts. ### Key Classes/Functions: - **Axes3D.draw()** - This method is responsible for rendering the 3D axes and likely doesn't check the visibility flag before proceeding with rendering. It needs to be modified to respect the visibility attribute. - **Artist.set_visible()** - The base implementation that sets the visibility flag which should control whether elements are drawn. Understanding how this interacts with 3D projections is crucial. - **Axes3D.set_frame_on()** - A related visibility method that controls the visibility of the 3D axes panels, but is not sufficient for full visibility control. ### Areas of Interest: - The parent-child relationship between artists in matplotlib and how visibility should propagate - The rendering pipeline for 3D projections and how it differs from standard 2D rendering - How visibility checks are implemented in regular matplotlib elements vs. 3D-specific elements - Whether 3D elements (planes, spines, etc.) need special handling for visibility ## Fix Hints ### High Confidence Locations: - The `Axes3D.draw(self, renderer)` method needs to be modified to check the visibility flag before rendering any components - A proper `set_visible()` method may need to be implemented in the `Axes3D` class to override the parent class method for 3D-specific handling ### Implementation Hints: - The simplest fix would likely be to modify the `draw()` method in `Axes3D` to include an early return if `self._visible` is `False` - Alternatively, ensure that the visibility check propagates to all components of the 3D axes - Any new implementation should maintain consistency with how visibility works in regular matplotlib axes ### Alternative Hypotheses: - The issue might not be in the visibility flag itself but in how 3D axes handle the parent-child relationship between artists - There could be a special case in 3D rendering that intentionally ignores visibility flags for performance reasons or due to technical limitations - The Qt5Agg backend might have specific issues with 3D visibility that other backends don't have, although this is less likely as the issue appears to be in the core 3D implementation - Multiple drawing paths might exist in 3D projections, and not all properly check visibility
Please try to boil down the problem to a minimal example when reporting issues. I've now done that for you: ``` import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw={'projection': '3d'}) ax1.scatter(1,1,1) ax2.scatter(1,1,1, c='r') ax1.set_visible(False) plt.show() ``` **Output** ![grafik](https://user-images.githubusercontent.com/2836374/174673179-f5b14df5-7689-49eb-995a-4c97e31c3c43.png) **Expected** The left axes should be invisible.
2022-06-21T02:41:34Z
3.5
["lib/mpl_toolkits/tests/test_mplot3d.py::test_invisible_axes[png]"]
["lib/matplotlib/tests/test_axes.py::test_invisible_axes[png]", "lib/matplotlib/tests/test_axes.py::test_get_labels", "lib/matplotlib/tests/test_axes.py::test_label_loc_vertical[png]", "lib/matplotlib/tests/test_axes.py::test_label_loc_vertical[pdf]", "lib/matplotlib/tests/test_axes.py::test_label_loc_horizontal[png]", "lib/matplotlib/tests/test_axes.py::test_label_loc_horizontal[pdf]", "lib/matplotlib/tests/test_axes.py::test_label_loc_rc[png]", "lib/matplotlib/tests/test_axes.py::test_label_loc_rc[pdf]", "lib/matplotlib/tests/test_axes.py::test_label_shift", "lib/matplotlib/tests/test_axes.py::test_acorr[png]", "lib/matplotlib/tests/test_axes.py::test_spy[png]", "lib/matplotlib/tests/test_axes.py::test_spy_invalid_kwargs", "lib/matplotlib/tests/test_axes.py::test_matshow[png]", "lib/matplotlib/tests/test_axes.py::test_formatter_ticker[png]", "lib/matplotlib/tests/test_axes.py::test_formatter_ticker[pdf]", "lib/matplotlib/tests/test_axes.py::test_funcformatter_auto_formatter", "lib/matplotlib/tests/test_axes.py::test_strmethodformatter_auto_formatter", "lib/matplotlib/tests/test_axes.py::test_twin_axis_locators_formatters[png]", "lib/matplotlib/tests/test_axes.py::test_twin_axis_locators_formatters[pdf]", "lib/matplotlib/tests/test_axes.py::test_twinx_cla", "lib/matplotlib/tests/test_axes.py::test_twin_logscale[png-x]", "lib/matplotlib/tests/test_axes.py::test_twin_logscale[png-y]", "lib/matplotlib/tests/test_axes.py::test_twinx_axis_scales[png]", "lib/matplotlib/tests/test_axes.py::test_twin_inherit_autoscale_setting", "lib/matplotlib/tests/test_axes.py::test_inverted_cla", "lib/matplotlib/tests/test_axes.py::test_cla_not_redefined", "lib/matplotlib/tests/test_axes.py::test_minorticks_on_rcParams_both[png]", "lib/matplotlib/tests/test_axes.py::test_autoscale_tiny_range[png]", "lib/matplotlib/tests/test_axes.py::test_autoscale_tiny_range[pdf]", "lib/matplotlib/tests/test_axes.py::test_autoscale_tight", "lib/matplotlib/tests/test_axes.py::test_autoscale_log_shared", "lib/matplotlib/tests/test_axes.py::test_use_sticky_edges", "lib/matplotlib/tests/test_axes.py::test_sticky_shared_axes[png]", "lib/matplotlib/tests/test_axes.py::test_basic_annotate[png]", "lib/matplotlib/tests/test_axes.py::test_basic_annotate[pdf]", "lib/matplotlib/tests/test_axes.py::test_arrow_simple[png]", "lib/matplotlib/tests/test_axes.py::test_arrow_empty", "lib/matplotlib/tests/test_axes.py::test_arrow_in_view", "lib/matplotlib/tests/test_axes.py::test_annotate_default_arrow", "lib/matplotlib/tests/test_axes.py::test_annotate_signature", "lib/matplotlib/tests/test_axes.py::test_fill_units[png]", "lib/matplotlib/tests/test_axes.py::test_plot_format_kwarg_redundant", "lib/matplotlib/tests/test_axes.py::test_errorbar_dashes[png]", "lib/matplotlib/tests/test_axes.py::test_single_point[png]", "lib/matplotlib/tests/test_axes.py::test_single_point[pdf]", "lib/matplotlib/tests/test_axes.py::test_single_date[png]", "lib/matplotlib/tests/test_axes.py::test_shaped_data[png]", "lib/matplotlib/tests/test_axes.py::test_structured_data", "lib/matplotlib/tests/test_axes.py::test_aitoff_proj[png]", "lib/matplotlib/tests/test_axes.py::test_axvspan_epoch[png]", "lib/matplotlib/tests/test_axes.py::test_axvspan_epoch[pdf]", "lib/matplotlib/tests/test_axes.py::test_axhspan_epoch[png]", "lib/matplotlib/tests/test_axes.py::test_axhspan_epoch[pdf]", "lib/matplotlib/tests/test_axes.py::test_hexbin_extent[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_empty[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_pickable", "lib/matplotlib/tests/test_axes.py::test_hexbin_log[png]", "lib/matplotlib/tests/test_axes.py::test_hexbin_log_clim", "lib/matplotlib/tests/test_axes.py::test_inverted_limits", "lib/matplotlib/tests/test_axes.py::test_nonfinite_limits[png]", "lib/matplotlib/tests/test_axes.py::test_nonfinite_limits[pdf]", "lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-scatter]", "lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-plot]", "lib/matplotlib/tests/test_axes.py::test_limits_empty_data[png-fill_between]", "lib/matplotlib/tests/test_axes.py::test_imshow[png]", "lib/matplotlib/tests/test_axes.py::test_imshow[pdf]", "lib/matplotlib/tests/test_axes.py::test_imshow_clip[png]", "lib/matplotlib/tests/test_axes.py::test_imshow_clip[pdf]", "lib/matplotlib/tests/test_axes.py::test_imshow_norm_vminvmax", "lib/matplotlib/tests/test_axes.py::test_polycollection_joinstyle[png]", "lib/matplotlib/tests/test_axes.py::test_polycollection_joinstyle[pdf]", "lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_x_input]", "lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_y1_input]", "lib/matplotlib/tests/test_axes.py::test_fill_between_input[2d_y2_input]", "lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_y_input]", "lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_x1_input]", "lib/matplotlib/tests/test_axes.py::test_fill_betweenx_input[2d_x2_input]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate[png]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate[pdf]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_decreasing[png]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_decreasing[pdf]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_nan[png]", "lib/matplotlib/tests/test_axes.py::test_fill_between_interpolate_nan[pdf]", "lib/matplotlib/tests/test_axes.py::test_symlog[pdf]", "lib/matplotlib/tests/test_axes.py::test_symlog2[pdf]", "lib/matplotlib/tests/test_axes.py::test_pcolorargs_5205", "lib/matplotlib/tests/test_axes.py::test_pcolormesh[png]", "lib/matplotlib/tests/test_axes.py::test_pcolormesh[pdf]", "lib/matplotlib/tests/test_axes.py::test_pcolormesh_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_pcolormesh_alpha[pdf]", "lib/matplotlib/tests/test_axes.py::test_pcolormesh_datetime_axis[png]", "lib/matplotlib/tests/test_axes.py::test_pcolor_datetime_axis[png]", "lib/matplotlib/tests/test_axes.py::test_pcolorargs", "lib/matplotlib/tests/test_axes.py::test_pcolornearest[png]", "lib/matplotlib/tests/test_axes.py::test_pcolornearestunits[png]", "lib/matplotlib/tests/test_axes.py::test_pcolorflaterror", "lib/matplotlib/tests/test_axes.py::test_pcolorauto[png-False]", "lib/matplotlib/tests/test_axes.py::test_pcolorauto[png-True]", "lib/matplotlib/tests/test_axes.py::test_canonical[png]", "lib/matplotlib/tests/test_axes.py::test_canonical[pdf]", "lib/matplotlib/tests/test_axes.py::test_arc_angles[png]", "lib/matplotlib/tests/test_axes.py::test_arc_ellipse[png]", "lib/matplotlib/tests/test_axes.py::test_arc_ellipse[pdf]", "lib/matplotlib/tests/test_axes.py::test_marker_as_markerstyle", "lib/matplotlib/tests/test_axes.py::test_markevery[png]", "lib/matplotlib/tests/test_axes.py::test_markevery[pdf]", "lib/matplotlib/tests/test_axes.py::test_markevery_line[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_line[pdf]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales[pdf]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_zoomed[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_zoomed[pdf]", "lib/matplotlib/tests/test_axes.py::test_markevery_log_scales[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_log_scales[pdf]", "lib/matplotlib/tests/test_axes.py::test_markevery_polar[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_polar[pdf]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_nans[png]", "lib/matplotlib/tests/test_axes.py::test_markevery_linear_scales_nans[pdf]", "lib/matplotlib/tests/test_axes.py::test_marker_edges[png]", "lib/matplotlib/tests/test_axes.py::test_marker_edges[pdf]", "lib/matplotlib/tests/test_axes.py::test_bar_tick_label_single[png]", "lib/matplotlib/tests/test_axes.py::test_nan_bar_values", "lib/matplotlib/tests/test_axes.py::test_bar_ticklabel_fail", "lib/matplotlib/tests/test_axes.py::test_bar_tick_label_multiple[png]", "lib/matplotlib/tests/test_axes.py::test_bar_tick_label_multiple_old_alignment[png]", "lib/matplotlib/tests/test_axes.py::test_bar_decimal_center[png]", "lib/matplotlib/tests/test_axes.py::test_barh_decimal_center[png]", "lib/matplotlib/tests/test_axes.py::test_bar_decimal_width[png]", "lib/matplotlib/tests/test_axes.py::test_barh_decimal_height[png]", "lib/matplotlib/tests/test_axes.py::test_bar_color_none_alpha", "lib/matplotlib/tests/test_axes.py::test_bar_edgecolor_none_alpha", "lib/matplotlib/tests/test_axes.py::test_barh_tick_label[png]", "lib/matplotlib/tests/test_axes.py::test_bar_timedelta", "lib/matplotlib/tests/test_axes.py::test_boxplot_dates_pandas", "lib/matplotlib/tests/test_axes.py::test_boxplot_capwidths", "lib/matplotlib/tests/test_axes.py::test_pcolor_regression", "lib/matplotlib/tests/test_axes.py::test_bar_pandas", "lib/matplotlib/tests/test_axes.py::test_bar_pandas_indexed", "lib/matplotlib/tests/test_axes.py::test_bar_hatches[png]", "lib/matplotlib/tests/test_axes.py::test_bar_hatches[pdf]", "lib/matplotlib/tests/test_axes.py::test_pandas_minimal_plot", "lib/matplotlib/tests/test_axes.py::test_hist_log[png]", "lib/matplotlib/tests/test_axes.py::test_hist_log[pdf]", "lib/matplotlib/tests/test_axes.py::test_hist_log_2[png]", "lib/matplotlib/tests/test_axes.py::test_hist_log_barstacked", "lib/matplotlib/tests/test_axes.py::test_hist_bar_empty[png]", "lib/matplotlib/tests/test_axes.py::test_hist_float16", "lib/matplotlib/tests/test_axes.py::test_hist_step_empty[png]", "lib/matplotlib/tests/test_axes.py::test_hist_step_filled[png]", "lib/matplotlib/tests/test_axes.py::test_hist_density[png]", "lib/matplotlib/tests/test_axes.py::test_hist_unequal_bins_density", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[date2num]", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[datetime.datetime]", "lib/matplotlib/tests/test_axes.py::test_hist_datetime_datasets_bins[np.datetime64]", "lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data0-1]", "lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data1-1]", "lib/matplotlib/tests/test_axes.py::test_hist_with_empty_input[data2-2]", "lib/matplotlib/tests/test_axes.py::test_hist_zorder[bar-1]", "lib/matplotlib/tests/test_axes.py::test_hist_zorder[step-2]", "lib/matplotlib/tests/test_axes.py::test_hist_zorder[stepfilled-1]", "lib/matplotlib/tests/test_axes.py::test_stairs[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_fill[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_update[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_baseline_0[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_empty", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_nan", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_mismatch", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_update", "lib/matplotlib/tests/test_axes.py::test_stairs_invalid_update2", "lib/matplotlib/tests/test_axes.py::test_stairs_options[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_datetime[png]", "lib/matplotlib/tests/test_axes.py::test_stairs_edge_handling[png]", "lib/matplotlib/tests/test_axes.py::test_contour_hatching[png]", "lib/matplotlib/tests/test_axes.py::test_contour_hatching[pdf]", "lib/matplotlib/tests/test_axes.py::test_contour_colorbar[png]", "lib/matplotlib/tests/test_axes.py::test_contour_colorbar[pdf]", "lib/matplotlib/tests/test_axes.py::test_hist2d[png]", "lib/matplotlib/tests/test_axes.py::test_hist2d[pdf]", "lib/matplotlib/tests/test_axes.py::test_hist2d_transpose[png]", "lib/matplotlib/tests/test_axes.py::test_hist2d_transpose[pdf]", "lib/matplotlib/tests/test_axes.py::test_hist2d_density", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_plot[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_plot[pdf]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_marker[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_2D[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_decimal[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_color", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfilled", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_unfillable", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_size_arg_size", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_edgecolor_RGB", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_invalid_color[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_no_invalid_color[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_norm_vminvmax", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_single_point[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_different_shapes[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[0.5-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case1-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[red-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[none-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[None-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case5-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[jaune-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case7-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case8-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case9-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case10-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case11-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case12-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case13-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case14-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case15-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case16-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case17-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case18-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case19-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case20-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case21-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case22-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case23-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case24-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case25-None]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case26-shape]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case27-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case28-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_c[c_case29-conversion]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_single_color_c[png]", "lib/matplotlib/tests/test_axes.py::TestScatter::test_scatter_linewidths", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params0-expected_result0]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params1-expected_result1]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params2-expected_result2]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params3-expected_result3]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args[params4-expected_result4]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs0-None]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs1-None]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs2-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs3-expected_edgecolors3]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs4-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs5-face]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs6-none]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs7-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs8-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs9-r]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_edgecolors[kwargs10-g]", "lib/matplotlib/tests/test_axes.py::test_parse_scatter_color_args_error", "lib/matplotlib/tests/test_axes.py::test_as_mpl_axes_api", "lib/matplotlib/tests/test_axes.py::test_pyplot_axes", "lib/matplotlib/tests/test_axes.py::test_log_scales", "lib/matplotlib/tests/test_axes.py::test_log_scales_no_data", "lib/matplotlib/tests/test_axes.py::test_log_scales_invalid", "lib/matplotlib/tests/test_axes.py::test_stackplot[png]", "lib/matplotlib/tests/test_axes.py::test_stackplot[pdf]", "lib/matplotlib/tests/test_axes.py::test_stackplot_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_stackplot_baseline[pdf]", "lib/matplotlib/tests/test_axes.py::test_bxp_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_rangewhis[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_percentilewhis[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_with_xlabels[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_horizontal[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_with_ylabels[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_patchartist[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custompatchartist[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customoutlier[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_showcustommean[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custombox[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custommedian[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customcap[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customwhisker[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_shownotches[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_nocaps[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_nobox[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_no_flier_stats[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_showmean[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_showmeanasline[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_scalarwidth[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_customwidths[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custompositions[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_bad_widths", "lib/matplotlib/tests/test_axes.py::test_bxp_bad_positions", "lib/matplotlib/tests/test_axes.py::test_bxp_custom_capwidths[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_custom_capwidth[png]", "lib/matplotlib/tests/test_axes.py::test_bxp_bad_capwidths", "lib/matplotlib/tests/test_axes.py::test_boxplot[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot[pdf]", "lib/matplotlib/tests/test_axes.py::test_boxplot_custom_capwidths[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_sym2[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_sym[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_autorange_whiskers[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_rc_parameters[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_rc_parameters[pdf]", "lib/matplotlib/tests/test_axes.py::test_boxplot_with_CIarray[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_no_weird_whisker[png]", "lib/matplotlib/tests/test_axes.py::test_boxplot_bad_medians", "lib/matplotlib/tests/test_axes.py::test_boxplot_bad_ci", "lib/matplotlib/tests/test_axes.py::test_boxplot_zorder", "lib/matplotlib/tests/test_axes.py::test_boxplot_marker_behavior", "lib/matplotlib/tests/test_axes.py::test_boxplot_mod_artist_after_plotting[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showmeans[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showextrema[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showmedians[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_showall[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_custompoints_10[png]", "lib/matplotlib/tests/test_axes.py::test_vert_violinplot_custompoints_200[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_baseline[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showmedians[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showmeans[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showextrema[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_showall[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_custompoints_10[png]", "lib/matplotlib/tests/test_axes.py::test_horiz_violinplot_custompoints_200[png]", "lib/matplotlib/tests/test_axes.py::test_violinplot_bad_positions", "lib/matplotlib/tests/test_axes.py::test_violinplot_bad_widths", "lib/matplotlib/tests/test_axes.py::test_violinplot_bad_quantiles", "lib/matplotlib/tests/test_axes.py::test_violinplot_outofrange_quantiles", "lib/matplotlib/tests/test_axes.py::test_violinplot_single_list_quantiles[png]", "lib/matplotlib/tests/test_axes.py::test_violinplot_pandas_series[png]", "lib/matplotlib/tests/test_axes.py::test_manage_xticks", "lib/matplotlib/tests/test_axes.py::test_boxplot_not_single", "lib/matplotlib/tests/test_axes.py::test_tick_space_size_0", "lib/matplotlib/tests/test_axes.py::test_errorbar[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar[pdf]", "lib/matplotlib/tests/test_axes.py::test_errorbar_colorcycle", "lib/matplotlib/tests/test_axes.py::test_errorbar_cycle_ecolor[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_cycle_ecolor[pdf]", "lib/matplotlib/tests/test_axes.py::test_errorbar_shape", "lib/matplotlib/tests/test_axes.py::test_errorbar_limits[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_limits[pdf]", "lib/matplotlib/tests/test_axes.py::test_errorbar_nonefmt", "lib/matplotlib/tests/test_axes.py::test_errorbar_line_specific_kwargs", "lib/matplotlib/tests/test_axes.py::test_errorbar_with_prop_cycle[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_every_invalid", "lib/matplotlib/tests/test_axes.py::test_xerr_yerr_not_negative", "lib/matplotlib/tests/test_axes.py::test_errorbar_every[png]", "lib/matplotlib/tests/test_axes.py::test_errorbar_every[pdf]", "lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[elinewidth0]", "lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[elinewidth1]", "lib/matplotlib/tests/test_axes.py::test_errorbar_linewidth_type[1]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled[pdf]", "lib/matplotlib/tests/test_axes.py::test_hist_offset[png]", "lib/matplotlib/tests/test_axes.py::test_hist_offset[pdf]", "lib/matplotlib/tests/test_axes.py::test_hist_step[png]", "lib/matplotlib/tests/test_axes.py::test_hist_step_horiz[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_weighted[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_weighted[pdf]", "lib/matplotlib/tests/test_axes.py::test_stem[png-w/", "lib/matplotlib/tests/test_axes.py::test_stem[png-w/o", "lib/matplotlib/tests/test_axes.py::test_stem_args", "lib/matplotlib/tests/test_axes.py::test_stem_dates", "lib/matplotlib/tests/test_axes.py::test_stem_orientation[png-w/", "lib/matplotlib/tests/test_axes.py::test_stem_orientation[png-w/o", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_alpha[pdf]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_step[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_step[pdf]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_density[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_density[pdf]", "lib/matplotlib/tests/test_axes.py::test_hist_step_bottom[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stepfilled_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_step_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stepfilled_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_step_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_step_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_stepfilled_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_step_bottom_geometry", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_bar[png]", "lib/matplotlib/tests/test_axes.py::test_hist_stacked_bar[pdf]", "lib/matplotlib/tests/test_axes.py::test_hist_barstacked_bottom_unchanged", "lib/matplotlib/tests/test_axes.py::test_hist_emptydata", "lib/matplotlib/tests/test_axes.py::test_hist_labels", "lib/matplotlib/tests/test_axes.py::test_transparent_markers[png]", "lib/matplotlib/tests/test_axes.py::test_transparent_markers[pdf]", "lib/matplotlib/tests/test_axes.py::test_rgba_markers[png]", "lib/matplotlib/tests/test_axes.py::test_rgba_markers[pdf]", "lib/matplotlib/tests/test_axes.py::test_mollweide_grid[png]", "lib/matplotlib/tests/test_axes.py::test_mollweide_grid[pdf]", "lib/matplotlib/tests/test_axes.py::test_mollweide_forward_inverse_closure", "lib/matplotlib/tests/test_axes.py::test_mollweide_inverse_forward_closure", "lib/matplotlib/tests/test_axes.py::test_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_alpha[pdf]", "lib/matplotlib/tests/test_axes.py::test_eventplot[png]", "lib/matplotlib/tests/test_axes.py::test_eventplot[pdf]", "lib/matplotlib/tests/test_axes.py::test_eventplot_defaults[png]", "lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_colors[colors2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_problem_kwargs[png]", "lib/matplotlib/tests/test_axes.py::test_empty_eventplot", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[None-data2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[vertical-data2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data0]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data1]", "lib/matplotlib/tests/test_axes.py::test_eventplot_orientation[horizontal-data2]", "lib/matplotlib/tests/test_axes.py::test_eventplot_units_list[png]", "lib/matplotlib/tests/test_axes.py::test_marker_styles[png]", "lib/matplotlib/tests/test_axes.py::test_markers_fillstyle_rcparams[png]", "lib/matplotlib/tests/test_axes.py::test_vertex_markers[png]", "lib/matplotlib/tests/test_axes.py::test_eb_line_zorder[png]", "lib/matplotlib/tests/test_axes.py::test_eb_line_zorder[pdf]", "lib/matplotlib/tests/test_axes.py::test_axline_loglog[png]", "lib/matplotlib/tests/test_axes.py::test_axline_loglog[pdf]", "lib/matplotlib/tests/test_axes.py::test_axline[png]", "lib/matplotlib/tests/test_axes.py::test_axline[pdf]", "lib/matplotlib/tests/test_axes.py::test_axline_transaxes[png]", "lib/matplotlib/tests/test_axes.py::test_axline_transaxes[pdf]", "lib/matplotlib/tests/test_axes.py::test_axline_transaxes_panzoom[png]", "lib/matplotlib/tests/test_axes.py::test_axline_transaxes_panzoom[pdf]", "lib/matplotlib/tests/test_axes.py::test_axline_args", "lib/matplotlib/tests/test_axes.py::test_vlines[png]", "lib/matplotlib/tests/test_axes.py::test_vlines_default", "lib/matplotlib/tests/test_axes.py::test_hlines[png]", "lib/matplotlib/tests/test_axes.py::test_hlines_default", "lib/matplotlib/tests/test_axes.py::test_lines_with_colors[png-data0]", "lib/matplotlib/tests/test_axes.py::test_lines_with_colors[png-data1]", "lib/matplotlib/tests/test_axes.py::test_step_linestyle[png]", "lib/matplotlib/tests/test_axes.py::test_step_linestyle[pdf]", "lib/matplotlib/tests/test_axes.py::test_mixed_collection[png]", "lib/matplotlib/tests/test_axes.py::test_mixed_collection[pdf]", "lib/matplotlib/tests/test_axes.py::test_subplot_key_hash", "lib/matplotlib/tests/test_axes.py::test_specgram[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_magnitude[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_angle[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_fs_none", "lib/matplotlib/tests/test_axes.py::test_specgram_origin_rcparam[png]", "lib/matplotlib/tests/test_axes.py::test_specgram_origin_kwarg", "lib/matplotlib/tests/test_axes.py::test_psd_csd[png]", "lib/matplotlib/tests/test_axes.py::test_spectrum[png]", "lib/matplotlib/tests/test_axes.py::test_psd_csd_edge_cases", "lib/matplotlib/tests/test_axes.py::test_twin_remove[png]", "lib/matplotlib/tests/test_axes.py::test_twin_spines[png]", "lib/matplotlib/tests/test_axes.py::test_twin_spines_on_top[png]", "lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[both-True-True]", "lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[major-True-False]", "lib/matplotlib/tests/test_axes.py::test_rcparam_grid_minor[minor-False-True]", "lib/matplotlib/tests/test_axes.py::test_grid", "lib/matplotlib/tests/test_axes.py::test_reset_grid", "lib/matplotlib/tests/test_axes.py::test_reset_ticks[png]", "lib/matplotlib/tests/test_axes.py::test_vline_limit", "lib/matplotlib/tests/test_axes.py::test_axline_minmax[axvline-axhline-args0]", "lib/matplotlib/tests/test_axes.py::test_axline_minmax[axvspan-axhspan-args1]", "lib/matplotlib/tests/test_axes.py::test_empty_shared_subplots", "lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_1", "lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_2", "lib/matplotlib/tests/test_axes.py::test_shared_with_aspect_3", "lib/matplotlib/tests/test_axes.py::test_shared_aspect_error", "lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args0-kwargs0-axis\\\\(\\\\)", "lib/matplotlib/tests/test_axes.py::test_axis_errors[ValueError-args1-kwargs1-Unrecognized", "lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args2-kwargs2-the", "lib/matplotlib/tests/test_axes.py::test_axis_errors[TypeError-args3-kwargs3-axis\\\\(\\\\)", "lib/matplotlib/tests/test_axes.py::test_axis_method_errors", "lib/matplotlib/tests/test_axes.py::test_twin_with_aspect[x]", "lib/matplotlib/tests/test_axes.py::test_twin_with_aspect[y]", "lib/matplotlib/tests/test_axes.py::test_relim_visible_only", "lib/matplotlib/tests/test_axes.py::test_text_labelsize", "lib/matplotlib/tests/test_axes.py::test_pie_default[png]", "lib/matplotlib/tests/test_axes.py::test_pie_linewidth_0[png]", "lib/matplotlib/tests/test_axes.py::test_pie_center_radius[png]", "lib/matplotlib/tests/test_axes.py::test_pie_linewidth_2[png]", "lib/matplotlib/tests/test_axes.py::test_pie_ccw_true[png]", "lib/matplotlib/tests/test_axes.py::test_pie_frame_grid[png]", "lib/matplotlib/tests/test_axes.py::test_pie_rotatelabels_true[png]", "lib/matplotlib/tests/test_axes.py::test_pie_nolabel_but_legend[png]", "lib/matplotlib/tests/test_axes.py::test_pie_textprops", "lib/matplotlib/tests/test_axes.py::test_pie_get_negative_values", "lib/matplotlib/tests/test_axes.py::test_normalize_kwarg_pie", "lib/matplotlib/tests/test_axes.py::test_set_get_ticklabels[png]", "lib/matplotlib/tests/test_axes.py::test_set_ticks_with_labels[png]", "lib/matplotlib/tests/test_axes.py::test_set_noniterable_ticklabels", "lib/matplotlib/tests/test_axes.py::test_subsampled_ticklabels", "lib/matplotlib/tests/test_axes.py::test_mismatched_ticklabels", "lib/matplotlib/tests/test_axes.py::test_empty_ticks_fixed_loc", "lib/matplotlib/tests/test_axes.py::test_retain_tick_visibility[png]", "lib/matplotlib/tests/test_axes.py::test_tick_label_update", "lib/matplotlib/tests/test_axes.py::test_o_marker_path_snap[png]", "lib/matplotlib/tests/test_axes.py::test_margins", "lib/matplotlib/tests/test_axes.py::test_set_margin_updates_limits", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args0-kwargs0-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args1-kwargs1-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args2-kwargs2-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[ValueError-args3-kwargs3-margin", "lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args4-kwargs4-Cannot", "lib/matplotlib/tests/test_axes.py::test_margins_errors[TypeError-args5-kwargs5-Must", "lib/matplotlib/tests/test_axes.py::test_length_one_hist", "lib/matplotlib/tests/test_axes.py::test_set_xy_bound", "lib/matplotlib/tests/test_axes.py::test_pathological_hexbin", "lib/matplotlib/tests/test_axes.py::test_color_None", "lib/matplotlib/tests/test_axes.py::test_color_alias", "lib/matplotlib/tests/test_axes.py::test_numerical_hist_label", "lib/matplotlib/tests/test_axes.py::test_unicode_hist_label", "lib/matplotlib/tests/test_axes.py::test_move_offsetlabel", "lib/matplotlib/tests/test_axes.py::test_rc_spines[png]", "lib/matplotlib/tests/test_axes.py::test_rc_grid[png]", "lib/matplotlib/tests/test_axes.py::test_rc_tick", "lib/matplotlib/tests/test_axes.py::test_rc_major_minor_tick", "lib/matplotlib/tests/test_axes.py::test_square_plot", "lib/matplotlib/tests/test_axes.py::test_bad_plot_args", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy0-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy1-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy2-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy3-PcolorImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data0-xy4-QuadMesh]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy0-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy1-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy2-AxesImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy3-PcolorImage]", "lib/matplotlib/tests/test_axes.py::test_pcolorfast[data1-xy4-QuadMesh]", "lib/matplotlib/tests/test_axes.py::test_shared_scale", "lib/matplotlib/tests/test_axes.py::test_shared_bool", "lib/matplotlib/tests/test_axes.py::test_violin_point_mass", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs0]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs1]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs2]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs3]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs4]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs5]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs6]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs7]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs8]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs9]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs10]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs11]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs12]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs13]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs14]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs15]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs16]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs17]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs18]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs19]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs20]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs21]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs22]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs23]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs24]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs25]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs26]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs27]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs28]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs29]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs30]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs31]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs32]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs33]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs34]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs35]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs36]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs37]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs38]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs39]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs40]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs41]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs42]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs43]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs44]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs45]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs46]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs47]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs48]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs49]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs50]", "lib/matplotlib/tests/test_axes.py::test_errorbar_inputs_shotgun[kwargs51]", "lib/matplotlib/tests/test_axes.py::test_dash_offset[png]", "lib/matplotlib/tests/test_axes.py::test_dash_offset[pdf]", "lib/matplotlib/tests/test_axes.py::test_title_pad", "lib/matplotlib/tests/test_axes.py::test_title_location_roundtrip", "lib/matplotlib/tests/test_axes.py::test_title_location_shared[True]", "lib/matplotlib/tests/test_axes.py::test_title_location_shared[False]", "lib/matplotlib/tests/test_axes.py::test_loglog[png]", "lib/matplotlib/tests/test_axes.py::test_loglog_nonpos[png]", "lib/matplotlib/tests/test_axes.py::test_axes_margins", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[gca-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[gca-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots_shared-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[subplots_shared-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[add_axes-x]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes[add_axes-y]", "lib/matplotlib/tests/test_axes.py::test_remove_shared_axes_relim", "lib/matplotlib/tests/test_axes.py::test_shared_axes_autoscale", "lib/matplotlib/tests/test_axes.py::test_adjust_numtick_aspect", "lib/matplotlib/tests/test_axes.py::test_auto_numticks", "lib/matplotlib/tests/test_axes.py::test_auto_numticks_log", "lib/matplotlib/tests/test_axes.py::test_broken_barh_empty", "lib/matplotlib/tests/test_axes.py::test_broken_barh_timedelta", "lib/matplotlib/tests/test_axes.py::test_pandas_pcolormesh", "lib/matplotlib/tests/test_axes.py::test_pandas_indexing_dates", "lib/matplotlib/tests/test_axes.py::test_pandas_errorbar_indexing", "lib/matplotlib/tests/test_axes.py::test_pandas_index_shape", "lib/matplotlib/tests/test_axes.py::test_pandas_indexing_hist", "lib/matplotlib/tests/test_axes.py::test_pandas_bar_align_center", "lib/matplotlib/tests/test_axes.py::test_tick_apply_tickdir_deprecation", "lib/matplotlib/tests/test_axes.py::test_axis_set_tick_params_labelsize_labelcolor", "lib/matplotlib/tests/test_axes.py::test_axes_tick_params_gridlines", "lib/matplotlib/tests/test_axes.py::test_axes_tick_params_ylabelside", "lib/matplotlib/tests/test_axes.py::test_axes_tick_params_xlabelside", "lib/matplotlib/tests/test_axes.py::test_none_kwargs", "lib/matplotlib/tests/test_axes.py::test_bar_uint8", "lib/matplotlib/tests/test_axes.py::test_date_timezone_x[png]", "lib/matplotlib/tests/test_axes.py::test_date_timezone_y[png]", "lib/matplotlib/tests/test_axes.py::test_date_timezone_x_and_y[png]", "lib/matplotlib/tests/test_axes.py::test_axisbelow[png]", "lib/matplotlib/tests/test_axes.py::test_titletwiny", "lib/matplotlib/tests/test_axes.py::test_titlesetpos", "lib/matplotlib/tests/test_axes.py::test_title_xticks_top", "lib/matplotlib/tests/test_axes.py::test_title_xticks_top_both", "lib/matplotlib/tests/test_axes.py::test_title_above_offset[left", "lib/matplotlib/tests/test_axes.py::test_title_above_offset[center", "lib/matplotlib/tests/test_axes.py::test_title_above_offset[both", "lib/matplotlib/tests/test_axes.py::test_title_no_move_off_page", "lib/matplotlib/tests/test_axes.py::test_offset_label_color", "lib/matplotlib/tests/test_axes.py::test_offset_text_visible", "lib/matplotlib/tests/test_axes.py::test_large_offset", "lib/matplotlib/tests/test_axes.py::test_barb_units", "lib/matplotlib/tests/test_axes.py::test_quiver_units", "lib/matplotlib/tests/test_axes.py::test_bar_color_cycle", "lib/matplotlib/tests/test_axes.py::test_tick_param_label_rotation", "lib/matplotlib/tests/test_axes.py::test_fillbetween_cycle", "lib/matplotlib/tests/test_axes.py::test_log_margins", "lib/matplotlib/tests/test_axes.py::test_color_length_mismatch", "lib/matplotlib/tests/test_axes.py::test_eventplot_legend", "lib/matplotlib/tests/test_axes.py::test_bar_broadcast_args", "lib/matplotlib/tests/test_axes.py::test_invalid_axis_limits", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[symlog-symlog]", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[symlog-log]", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[log-symlog]", "lib/matplotlib/tests/test_axes.py::test_minorticks_on[log-log]", "lib/matplotlib/tests/test_axes.py::test_twinx_knows_limits", "lib/matplotlib/tests/test_axes.py::test_zero_linewidth", "lib/matplotlib/tests/test_axes.py::test_empty_errorbar_legend", "lib/matplotlib/tests/test_axes.py::test_plot_decimal[png]", "lib/matplotlib/tests/test_axes.py::test_markerfacecolor_none_alpha[png]", "lib/matplotlib/tests/test_axes.py::test_tick_padding_tightbbox", "lib/matplotlib/tests/test_axes.py::test_inset", "lib/matplotlib/tests/test_axes.py::test_zoom_inset", "lib/matplotlib/tests/test_axes.py::test_inset_polar[png]", "lib/matplotlib/tests/test_axes.py::test_inset_projection", "lib/matplotlib/tests/test_axes.py::test_inset_subclass", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[False-False]", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[False-True]", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[True-False]", "lib/matplotlib/tests/test_axes.py::test_indicate_inset_inverted[True-True]", "lib/matplotlib/tests/test_axes.py::test_set_position", "lib/matplotlib/tests/test_axes.py::test_spines_properbbox_after_zoom", "lib/matplotlib/tests/test_axes.py::test_gettightbbox_ignore_nan", "lib/matplotlib/tests/test_axes.py::test_scatter_series_non_zero_index", "lib/matplotlib/tests/test_axes.py::test_scatter_empty_data", "lib/matplotlib/tests/test_axes.py::test_annotate_across_transforms[png]", "lib/matplotlib/tests/test_axes.py::test_secondary_xy[png]", "lib/matplotlib/tests/test_axes.py::test_secondary_fail", "lib/matplotlib/tests/test_axes.py::test_secondary_resize", "lib/matplotlib/tests/test_axes.py::test_secondary_minorloc", "lib/matplotlib/tests/test_axes.py::test_secondary_formatter", "lib/matplotlib/tests/test_axes.py::test_secondary_repr", "lib/matplotlib/tests/test_axes.py::test_normal_axes", "lib/matplotlib/tests/test_axes.py::test_nodecorator", "lib/matplotlib/tests/test_axes.py::test_displaced_spine", "lib/matplotlib/tests/test_axes.py::test_tickdirs", "lib/matplotlib/tests/test_axes.py::test_minor_accountedfor", "lib/matplotlib/tests/test_axes.py::test_axis_bool_arguments[png]", "lib/matplotlib/tests/test_axes.py::test_axis_extent_arg", "lib/matplotlib/tests/test_axes.py::test_axis_extent_arg2", "lib/matplotlib/tests/test_axes.py::test_hist_auto_bins", "lib/matplotlib/tests/test_axes.py::test_hist_nan_data", "lib/matplotlib/tests/test_axes.py::test_hist_range_and_density", "lib/matplotlib/tests/test_axes.py::test_bar_errbar_zorder", "lib/matplotlib/tests/test_axes.py::test_set_ticks_inverted", "lib/matplotlib/tests/test_axes.py::test_aspect_nonlinear_adjustable_box", "lib/matplotlib/tests/test_axes.py::test_aspect_nonlinear_adjustable_datalim", "lib/matplotlib/tests/test_axes.py::test_box_aspect", "lib/matplotlib/tests/test_axes.py::test_box_aspect_custom_position", "lib/matplotlib/tests/test_axes.py::test_bbox_aspect_axes_init", "lib/matplotlib/tests/test_axes.py::test_redraw_in_frame", "lib/matplotlib/tests/test_axes.py::test_invisible_axes_events", "lib/matplotlib/tests/test_axes.py::test_xtickcolor_is_not_markercolor", "lib/matplotlib/tests/test_axes.py::test_ytickcolor_is_not_markercolor", "lib/matplotlib/tests/test_axes.py::test_unautoscale[True-x]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[True-y]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[False-x]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[False-y]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[None-x]", "lib/matplotlib/tests/test_axes.py::test_unautoscale[None-y]", "lib/matplotlib/tests/test_axes.py::test_polar_interpolation_steps_variable_r[png]", "lib/matplotlib/tests/test_axes.py::test_autoscale_tiny_sticky", "lib/matplotlib/tests/test_axes.py::test_xtickcolor_is_not_xticklabelcolor", "lib/matplotlib/tests/test_axes.py::test_ytickcolor_is_not_yticklabelcolor", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[xx-small]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[x-small]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[small]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[medium]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[large]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[x-large]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[xx-large]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[larger]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[smaller]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[8]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[10]", "lib/matplotlib/tests/test_axes.py::test_relative_ticklabel_sizes[12]", "lib/matplotlib/tests/test_axes.py::test_multiplot_autoscale", "lib/matplotlib/tests/test_axes.py::test_sharing_does_not_link_positions", "lib/matplotlib/tests/test_axes.py::test_2dcolor_plot[pdf]", "lib/matplotlib/tests/test_axes.py::test_shared_axes_clear[png]", "lib/matplotlib/tests/test_axes.py::test_shared_axes_retick", "lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[left]", "lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[center]", "lib/matplotlib/tests/test_axes.py::test_ylabel_ha_with_position[right]", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_vertical", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_vertical_yinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_yinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_xinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_horizontal_xyinverted", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_center", "lib/matplotlib/tests/test_axes.py::test_bar_label_location_errorbars", "lib/matplotlib/tests/test_axes.py::test_bar_label_fmt", "lib/matplotlib/tests/test_axes.py::test_bar_label_labels", "lib/matplotlib/tests/test_axes.py::test_bar_label_nan_ydata", "lib/matplotlib/tests/test_axes.py::test_bar_label_nan_ydata_inverted", "lib/matplotlib/tests/test_axes.py::test_nan_barlabels", "lib/matplotlib/tests/test_axes.py::test_patch_bounds", "lib/matplotlib/tests/test_axes.py::test_warn_ignored_scatter_kwargs", "lib/matplotlib/tests/test_axes.py::test_artist_sublists", "lib/matplotlib/tests/test_axes.py::test_empty_line_plots", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-f-'f'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-o+-'o\\\\+'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-:--':-'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-rk-'rk'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[None-:o-r-':o-r'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-f-'f'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-o+-'o\\\\+'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-:--':-'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-rk-'rk'", "lib/matplotlib/tests/test_axes.py::test_plot_format_errors[data1-:o-r-':o-r'", "lib/matplotlib/tests/test_axes.py::test_plot_format", "lib/matplotlib/tests/test_axes.py::test_automatic_legend", "lib/matplotlib/tests/test_axes.py::test_plot_errors", "lib/matplotlib/tests/test_axes.py::test_clim", "lib/matplotlib/tests/test_axes.py::test_bezier_autoscale", "lib/matplotlib/tests/test_axes.py::test_get_xticklabel", "lib/mpl_toolkits/tests/test_mplot3d.py::test_aspect_equal_error", "lib/mpl_toolkits/tests/test_mplot3d.py::test_bar3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_bar3d_colors", "lib/mpl_toolkits/tests/test_mplot3d.py::test_bar3d_shaded[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_bar3d_notshaded[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_bar3d_lightsource", "lib/mpl_toolkits/tests/test_mplot3d.py::test_contour3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_contourf3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_contourf3d_fill[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_contourf3d_extend[png-both-levels0]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_contourf3d_extend[png-min-levels1]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_contourf3d_extend[png-max-levels2]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_tricontour[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_contour3d_1d_input", "lib/mpl_toolkits/tests/test_mplot3d.py::test_lines3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_plot_scalar[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_mixedsubplots[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_tight_layout_text[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d_color[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d_modification[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d_sorting[png-True]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter3d_sorting[png-False]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_marker_draw_order_data_reversed[png--50]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_marker_draw_order_data_reversed[png-130]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_marker_draw_order_view_rotated[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_plot_3d_from_2d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_surface3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_surface3d_shaded[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_surface3d_masked[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_surface3d_masked_strides[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_text3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_text3d_modification[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_trisurf3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_trisurf3d_shaded[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_wireframe3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_wireframe3dzerocstride[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_wireframe3dzerorstride[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_wireframe3dzerostrideraises", "lib/mpl_toolkits/tests/test_mplot3d.py::test_mixedsamplesraises", "lib/mpl_toolkits/tests/test_mplot3d.py::test_quiver3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_quiver3d_empty[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_quiver3d_masked[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_patch_modification", "lib/mpl_toolkits/tests/test_mplot3d.py::test_patch_collection_modification[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_poly3dcollection_verts_validation", "lib/mpl_toolkits/tests/test_mplot3d.py::test_poly3dcollection_closed[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_poly_collection_2d_to_3d_empty", "lib/mpl_toolkits/tests/test_mplot3d.py::test_poly3dcollection_alpha[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_add_collection3d_zs_array[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_add_collection3d_zs_scalar[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_labelpad[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_cla[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_rotated[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_plotsurface_1d_raises", "lib/mpl_toolkits/tests/test_mplot3d.py::test_proj_transform", "lib/mpl_toolkits/tests/test_mplot3d.py::test_proj_axes_cube[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_proj_axes_cube_ortho[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_rot", "lib/mpl_toolkits/tests/test_mplot3d.py::test_world", "lib/mpl_toolkits/tests/test_mplot3d.py::test_lines_dists[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_lines_dists_nowarning", "lib/mpl_toolkits/tests/test_mplot3d.py::test_autoscale", "lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[True-x]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[True-y]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[True-z]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[False-x]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[False-y]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[False-z]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[None-x]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[None-y]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_unautoscale[None-z]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_focal_length_checks", "lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_focal_length[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_ortho[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_axes3d_isometric[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_xlim3d-left-inf]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_xlim3d-left-nan]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_xlim3d-right-inf]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_xlim3d-right-nan]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_ylim3d-bottom-inf]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_ylim3d-bottom-nan]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_ylim3d-top-inf]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_ylim3d-top-nan]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_zlim3d-bottom-inf]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_zlim3d-bottom-nan]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_zlim3d-top-inf]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_invalid_axes_limits[set_zlim3d-top-nan]", "lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_simple[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_edge_style[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_named_colors[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_rgb_data[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_alpha[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_xyz[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::TestVoxels::test_calling_conventions", "lib/mpl_toolkits/tests/test_mplot3d.py::test_line3d_set_get_data_3d", "lib/mpl_toolkits/tests/test_mplot3d.py::test_inverted[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_inverted_cla", "lib/mpl_toolkits/tests/test_mplot3d.py::test_ax3d_tickcolour", "lib/mpl_toolkits/tests/test_mplot3d.py::test_ticklabel_format[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_quiver3D_smoke[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_minor_ticks[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_errorbar3d_errorevery[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_errorbar3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_stem3d[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_equal_box_aspect[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_colorbar_pos", "lib/mpl_toolkits/tests/test_mplot3d.py::test_shared_axes_retick", "lib/mpl_toolkits/tests/test_mplot3d.py::test_pan", "lib/mpl_toolkits/tests/test_mplot3d.py::test_scalarmap_update[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_subfigure_simple", "lib/mpl_toolkits/tests/test_mplot3d.py::test_computed_zorder[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_scatter_spiral[png]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_view_init_vertical_axis[z-proj_expected0-axis_lines_expected0-tickdirs_expected0]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_view_init_vertical_axis[y-proj_expected1-axis_lines_expected1-tickdirs_expected1]", "lib/mpl_toolkits/tests/test_mplot3d.py::test_view_init_vertical_axis[x-proj_expected2-axis_lines_expected2-tickdirs_expected2]"]
de98877e3dc45de8dd441d008f23d88738dc015d
matplotlib/matplotlib
matplotlib__matplotlib-22711
f670fe78795b18eb1118707721852209cd77ad51
diff --git a/lib/matplotlib/widgets.py b/lib/matplotlib/widgets.py --- a/lib/matplotlib/widgets.py +++ b/lib/matplotlib/widgets.py @@ -813,7 +813,10 @@ def _update_val_from_pos(self, pos): val = self._max_in_bounds(pos) self.set_max(val) if self._active_handle: - self._active_handle.set_xdata([val]) + if self.orientation == "vertical": + self._active_handle.set_ydata([val]) + else: + self._active_handle.set_xdata([val]) def _update(self, event): """Update the slider position.""" @@ -836,11 +839,16 @@ def _update(self, event): return # determine which handle was grabbed - handle = self._handles[ - np.argmin( + if self.orientation == "vertical": + handle_index = np.argmin( + np.abs([h.get_ydata()[0] - event.ydata for h in self._handles]) + ) + else: + handle_index = np.argmin( np.abs([h.get_xdata()[0] - event.xdata for h in self._handles]) ) - ] + handle = self._handles[handle_index] + # these checks ensure smooth behavior if the handles swap which one # has a higher value. i.e. if one is dragged over and past the other. if handle is not self._active_handle: @@ -904,14 +912,22 @@ def set_val(self, val): xy[2] = .75, val[1] xy[3] = .75, val[0] xy[4] = .25, val[0] + + self._handles[0].set_ydata([val[0]]) + self._handles[1].set_ydata([val[1]]) else: xy[0] = val[0], .25 xy[1] = val[0], .75 xy[2] = val[1], .75 xy[3] = val[1], .25 xy[4] = val[0], .25 + + self._handles[0].set_xdata([val[0]]) + self._handles[1].set_xdata([val[1]]) + self.poly.xy = xy self.valtext.set_text(self._format(val)) + if self.drawon: self.ax.figure.canvas.draw_idle() self.val = val
diff --git a/lib/matplotlib/tests/test_widgets.py b/lib/matplotlib/tests/test_widgets.py --- a/lib/matplotlib/tests/test_widgets.py +++ b/lib/matplotlib/tests/test_widgets.py @@ -1105,19 +1105,30 @@ def test_range_slider(orientation): # Check initial value is set correctly assert_allclose(slider.val, (0.1, 0.34)) + def handle_positions(slider): + if orientation == "vertical": + return [h.get_ydata()[0] for h in slider._handles] + else: + return [h.get_xdata()[0] for h in slider._handles] + slider.set_val((0.2, 0.6)) assert_allclose(slider.val, (0.2, 0.6)) + assert_allclose(handle_positions(slider), (0.2, 0.6)) + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) assert_allclose(box.get_points().flatten()[idx], [0.2, .25, 0.6, .75]) slider.set_val((0.2, 0.1)) assert_allclose(slider.val, (0.1, 0.2)) + assert_allclose(handle_positions(slider), (0.1, 0.2)) slider.set_val((-1, 10)) assert_allclose(slider.val, (0, 1)) + assert_allclose(handle_positions(slider), (0, 1)) slider.reset() - assert_allclose(slider.val, [0.1, 0.34]) + assert_allclose(slider.val, (0.1, 0.34)) + assert_allclose(handle_positions(slider), (0.1, 0.34)) def check_polygon_selector(event_sequence, expected_result, selections_count,
# RangeSlider Initial Value Bug: IndexError When Setting Initial Values ## Issue Description The RangeSlider widget in matplotlib (v3.5.1) fails when attempting to set initial values using the `valinit` parameter. The issue occurs in the `set_val` method of the `RangeSlider` class, where the code attempts to access index 4 of the polygon's vertex array (`xy[4]`), but this array only contains 4 elements (indices 0-3). This results in an IndexError, preventing users from initializing the RangeSlider with custom values. The problematic lines appear to be remnants of code that expected a 5-vertex polygon, while the actual implementation creates a 4-vertex rectangle. ## Reproduction Steps ```python import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import RangeSlider # generate a fake image np.random.seed(19680801) N = 128 img = np.random.randn(N, N) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) fig.subplots_adjust(bottom=0.25) im = axs[0].imshow(img) axs[1].hist(img.flatten(), bins='auto') axs[1].set_title('Histogram of pixel intensities') # Create the RangeSlider slider_ax = fig.add_axes([0.20, 0.1, 0.60, 0.03]) slider = RangeSlider(slider_ax, "Threshold", img.min(), img.max(),valinit=[0.0,0.0]) # Create the Vertical lines on the histogram lower_limit_line = axs[1].axvline(slider.val[0], color='k') upper_limit_line = axs[1].axvline(slider.val[1], color='k') def update(val): # Update the image's colormap im.norm.vmin = val[0] im.norm.vmax = val[1] # Update the position of the vertical lines lower_limit_line.set_xdata([val[0], val[0]]) upper_limit_line.set_xdata([val[1], val[1]]) # Redraw the figure to ensure it updates fig.canvas.draw_idle() slider.on_changed(update) plt.show() ``` **Error message:** ``` IndexError: index 4 is out of bounds for axis 0 with size 4 ``` **Technical details about what happens internally:** 1. The `RangeSlider` constructor calls `self.set_val(valinit)` during initialization 2. In `set_val`, the polygon vertices are updated based on slider values 3. The method attempts to set `xy[4]` for both vertical and horizontal orientations: - For vertical: `xy[4] = .25, val[0]` - For horizontal: `xy[4] = val[0], .25` 4. However, `xy` only contains indices 0-3, causing the IndexError ## Expected Behavior The RangeSlider should initialize successfully with the specified initial values. The slider should display with the handles positioned at the specified initial values and function properly afterward, allowing the user to adjust the range. ## Exploration Hints ### Files to Examine: - **lib/matplotlib/widgets.py** - Contains the `RangeSlider` class implementation. This file includes both the initialization of the slider's polygon (which has 4 vertices) and the problematic `set_val` method where the IndexError occurs when trying to access a non-existent 5th vertex. - **examples/widgets/range_slider.py** - Provides context for normal RangeSlider usage, though it doesn't demonstrate using the `valinit` parameter that triggers the bug. ### Key Classes/Functions: - **RangeSlider.__init__()** - Creates the slider with 4 vertices for the polygon and passes the `valinit` parameter to `set_val`. - **RangeSlider.set_val()** - Contains the bug around line 915 where `xy[4]` is accessed even though `xy` only has elements 0-3. This method is called during initialization when `valinit` is provided. ### Areas of Interest: - The polygon creation and manipulation logic between `__init__` and `set_val` needs investigation to understand why there's an inconsistency in the expected number of vertices. - The lines referencing `xy[4]` appear to be attempting to close the polygon by making the 5th vertex equal to the 1st vertex, but this may be unnecessary if matplotlib's Polygon class handles closure automatically. - The bug only manifests when `valinit` is provided, which suggests the normal slider interaction might use a different code path or handle the vertices differently. ## Fix Hints ### High Confidence Locations: - **lib/matplotlib/widgets.py**, lines 914-915 (for vertical orientation) and 921-922 (for horizontal orientation) - The problematic lines that attempt to access `xy[4]` should be commented out or removed as they reference a non-existent array index. ### Implementation Hints: 1. **Comment out the problematic lines**: The simplest fix is to comment out or remove the lines that attempt to set `xy[4]`: ```python # For vertical orientation # xy[4] = .25, val[0] # For horizontal orientation # xy[4] = val[0], .25 ``` 2. **Alternative approach**: If the 5th vertex is genuinely needed to close the polygon, the implementation could be modified to append a 5th vertex to the array: ```python # For vertical orientation xy = np.vstack([xy, [.25, val[0]]]) # For horizontal orientation xy = np.vstack([xy, [val[0], .25]]) ``` However, this approach is likely unnecessary as matplotlib's Polygon class typically doesn't require explicit closure of polygons. ### Alternative Hypotheses: 1. **Polygon evolution**: The code might have evolved from a version where the polygon had 5 vertices to one with 4 vertices, without updating all references to the vertex array. 2. **Automatic closure**: The implementation may have been assuming that matplotlib's Polygon class automatically closes the shape, but this behavior might vary across different matplotlib versions. 3. **Necessary redundancy**: The 5th vertex might actually be necessary for some specific rendering behavior or interaction handling that isn't apparent from the code snippets available. If this is true, the fix would involve ensuring the polygon has 5 vertices consistently. 4. **Backend differences**: There might be differences in how polygons are handled across different matplotlib backends, which could explain why this issue might not appear in all environments.
Huh, the polygon object must have changed inadvertently. Usually, you have to "close" the polygon by repeating the first vertex, but we make it possible for polygons to auto-close themselves. I wonder how (when?) this broke? On Tue, Mar 22, 2022 at 10:29 PM vpicouet ***@***.***> wrote: > Bug summary > > I think xy[4] = .25, val[0] should be commented in /matplotlib/widgets. > py", line 915, in set_val > as it prevents to initialized value for RangeSlider > Code for reproduction > > import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import RangeSlider > # generate a fake imagenp.random.seed(19680801)N = 128img = np.random.randn(N, N) > fig, axs = plt.subplots(1, 2, figsize=(10, 5))fig.subplots_adjust(bottom=0.25) > im = axs[0].imshow(img)axs[1].hist(img.flatten(), bins='auto')axs[1].set_title('Histogram of pixel intensities') > # Create the RangeSliderslider_ax = fig.add_axes([0.20, 0.1, 0.60, 0.03])slider = RangeSlider(slider_ax, "Threshold", img.min(), img.max(),valinit=[0.0,0.0]) > # Create the Vertical lines on the histogramlower_limit_line = axs[1].axvline(slider.val[0], color='k')upper_limit_line = axs[1].axvline(slider.val[1], color='k') > > def update(val): > # The val passed to a callback by the RangeSlider will > # be a tuple of (min, max) > > # Update the image's colormap > im.norm.vmin = val[0] > im.norm.vmax = val[1] > > # Update the position of the vertical lines > lower_limit_line.set_xdata([val[0], val[0]]) > upper_limit_line.set_xdata([val[1], val[1]]) > > # Redraw the figure to ensure it updates > fig.canvas.draw_idle() > > slider.on_changed(update)plt.show() > > Actual outcome > > File "<ipython-input-52-b704c53e18d4>", line 19, in <module> > slider = RangeSlider(slider_ax, "Threshold", img.min(), img.max(),valinit=[0.0,0.0]) > > File "/Users/Vincent/opt/anaconda3/envs/py38/lib/python3.8/site-packages/matplotlib/widgets.py", line 778, in __init__ > self.set_val(valinit) > > File "/Users/Vincent/opt/anaconda3/envs/py38/lib/python3.8/site-packages/matplotlib/widgets.py", line 915, in set_val > xy[4] = val[0], .25 > > IndexError: index 4 is out of bounds for axis 0 with size 4 > > Expected outcome > > range slider with user initial values > Additional information > > error can be > > > def set_val(self, val): > """ > Set slider value to *val*. > > Parameters > ---------- > val : tuple or array-like of float > """ > val = np.sort(np.asanyarray(val)) > if val.shape != (2,): > raise ValueError( > f"val must have shape (2,) but has shape {val.shape}" > ) > val[0] = self._min_in_bounds(val[0]) > val[1] = self._max_in_bounds(val[1]) > xy = self.poly.xy > if self.orientation == "vertical": > xy[0] = .25, val[0] > xy[1] = .25, val[1] > xy[2] = .75, val[1] > xy[3] = .75, val[0] > # xy[4] = .25, val[0] > else: > xy[0] = val[0], .25 > xy[1] = val[0], .75 > xy[2] = val[1], .75 > xy[3] = val[1], .25 > # xy[4] = val[0], .25 > self.poly.xy = xy > self.valtext.set_text(self._format(val)) > if self.drawon: > self.ax.figure.canvas.draw_idle() > self.val = val > if self.eventson: > self._observers.process("changed", val) > > > Operating system > > OSX > Matplotlib Version > > 3.5.1 > Matplotlib Backend > > *No response* > Python version > > 3.8 > Jupyter version > > *No response* > Installation > > pip > > — > Reply to this email directly, view it on GitHub > <https://github.com/matplotlib/matplotlib/issues/22686>, or unsubscribe > <https://github.com/notifications/unsubscribe-auth/AACHF6CW2HVLKT5Q56BVZDLVBJ6X7ANCNFSM5RMUEIDQ> > . > You are receiving this because you are subscribed to this thread.Message > ID: ***@***.***> > Yes, i might have been too fast, cause it allows to skip the error but then it seems that the polygon is not right... Let me know if you know how this should be solved... ![Capture d’écran, le 2022-03-22 à 23 20 23](https://user-images.githubusercontent.com/37241971/159617326-44c69bfc-bf0a-4f79-ab23-925c7066f2c2.jpg) So I think you found an edge case because your valinit has both values equal. This means that the poly object created by `axhspan` is not as large as the rest of the code expects. https://github.com/matplotlib/matplotlib/blob/11737d0694109f71d2603ba67d764aa2fb302761/lib/matplotlib/widgets.py#L722 A quick workaround is to have the valinit contain two different numbers (even if only minuscule difference) Yes you are right! Thanks a lot for digging into this!! Compare: ```python import matplotlib.pyplot as plt fig, ax = plt.subplots() poly_same_valinit = ax.axvspan(0, 0, 0, 1) poly_diff_valinit = ax.axvspan(0, .5, 0, 1) print(poly_same_valinit.xy.shape) print(poly_diff_valinit.xy.shape) ``` which gives: ``` (4, 2) (5, 2) ``` Two solutions spring to mind: 1. Easier option Throw an error in init if `valinit[0] == valinit[1]` 2. Maybe better option? Don't use axhspan and manually create the poly to ensure it always has the expected number of vertices Option 2 might be better yes @vpicouet any interest in opening a PR? I don't think I am qualified to do so, never opened a PR yet. RangeSlider might also contain another issue. When I call `RangeSlider.set_val([0.0,0.1])` It changes only the blue poly object and the range value on the right side of the slider not the dot: ![Capture d’écran, le 2022-03-25 à 15 53 44](https://user-images.githubusercontent.com/37241971/160191943-aef5fbe2-2f54-42ae-9719-23375767b212.jpg) > I don't think I am qualified to do so, never opened a PR yet. That's always true until you've opened your first one :). But I also understand that it can be intimidating. > RangeSlider might also contain another issue. > When I call RangeSlider.set_val([0.0,0.1]) > It changes only the blue poly object and the range value on the right side of the slider not the dot: oh hmm - good catch! may be worth opening a separate issue there as these are two distinct bugs and this one may be a bit more comlicated to fix. Haha true! I might try when I have more time! Throwing an error at least as I have never worked with axhspan and polys. Ok, openning another issue. Can I try working on this? @ianhi @vpicouet From the discussion, I could identify that a quick fix would be to use a try-except block to throw an error if valinit[0] == valinit[1] Please let me know your thoughts. Sure!
2022-03-27T00:34:37Z
3.5
["lib/matplotlib/tests/test_widgets.py::test_range_slider[horizontal]", "lib/matplotlib/tests/test_widgets.py::test_range_slider[vertical]"]
["lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[0-10-0-10-data]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[0-10-0-10-pixels]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[0-10-1-10.5-data]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[0-10-1-10.5-pixels]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[0-10-1-11-data]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[0-10-1-11-pixels]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-10.5-0-10-data]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-10.5-0-10-pixels]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-10.5-1-10.5-data]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-10.5-1-10.5-pixels]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-10.5-1-11-data]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-10.5-1-11-pixels]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-11-0-10-data]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-11-0-10-pixels]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-11-1-10.5-data]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-11-1-10.5-pixels]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-11-1-11-data]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_minspan[1-11-1-11-pixels]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_drag[True-new_center0]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_drag[False-new_center1]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_selector_set_props_handle_props", "lib/matplotlib/tests/test_widgets.py::test_rectangle_resize", "lib/matplotlib/tests/test_widgets.py::test_rectangle_add_state", "lib/matplotlib/tests/test_widgets.py::test_rectangle_resize_center[True]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_resize_center[False]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_resize_square[True]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_resize_square[False]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_resize_square_center", "lib/matplotlib/tests/test_widgets.py::test_rectangle_rotate[RectangleSelector]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_rotate[EllipseSelector]", "lib/matplotlib/tests/test_widgets.py::test_rectange_add_remove_set", "lib/matplotlib/tests/test_widgets.py::test_rectangle_resize_square_center_aspect[False]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_resize_square_center_aspect[True]", "lib/matplotlib/tests/test_widgets.py::test_ellipse", "lib/matplotlib/tests/test_widgets.py::test_rectangle_handles", "lib/matplotlib/tests/test_widgets.py::test_rectangle_selector_onselect[True]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_selector_onselect[False]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_selector_ignore_outside[True]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_selector_ignore_outside[False]", "lib/matplotlib/tests/test_widgets.py::test_span_selector", "lib/matplotlib/tests/test_widgets.py::test_span_selector_onselect[True]", "lib/matplotlib/tests/test_widgets.py::test_span_selector_onselect[False]", "lib/matplotlib/tests/test_widgets.py::test_span_selector_ignore_outside[True]", "lib/matplotlib/tests/test_widgets.py::test_span_selector_ignore_outside[False]", "lib/matplotlib/tests/test_widgets.py::test_span_selector_drag[True]", "lib/matplotlib/tests/test_widgets.py::test_span_selector_drag[False]", "lib/matplotlib/tests/test_widgets.py::test_span_selector_direction", "lib/matplotlib/tests/test_widgets.py::test_span_selector_set_props_handle_props", "lib/matplotlib/tests/test_widgets.py::test_selector_clear[span]", "lib/matplotlib/tests/test_widgets.py::test_selector_clear[rectangle]", "lib/matplotlib/tests/test_widgets.py::test_selector_clear_method[span]", "lib/matplotlib/tests/test_widgets.py::test_selector_clear_method[rectangle]", "lib/matplotlib/tests/test_widgets.py::test_span_selector_add_state", "lib/matplotlib/tests/test_widgets.py::test_tool_line_handle", "lib/matplotlib/tests/test_widgets.py::test_span_selector_bound[horizontal]", "lib/matplotlib/tests/test_widgets.py::test_span_selector_bound[vertical]", "lib/matplotlib/tests/test_widgets.py::test_lasso_selector", "lib/matplotlib/tests/test_widgets.py::test_CheckButtons", "lib/matplotlib/tests/test_widgets.py::test_TextBox[none]", "lib/matplotlib/tests/test_widgets.py::test_TextBox[toolbar2]", "lib/matplotlib/tests/test_widgets.py::test_TextBox[toolmanager]", "lib/matplotlib/tests/test_widgets.py::test_check_radio_buttons_image[png]", "lib/matplotlib/tests/test_widgets.py::test_check_bunch_of_radio_buttons[png]", "lib/matplotlib/tests/test_widgets.py::test_slider_slidermin_slidermax_invalid", "lib/matplotlib/tests/test_widgets.py::test_slider_slidermin_slidermax", "lib/matplotlib/tests/test_widgets.py::test_slider_valmin_valmax", "lib/matplotlib/tests/test_widgets.py::test_slider_valstep_snapping", "lib/matplotlib/tests/test_widgets.py::test_slider_horizontal_vertical", "lib/matplotlib/tests/test_widgets.py::test_slider_reset", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector[False]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector[True]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_set_props_handle_props[False]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_set_props_handle_props[True]", "lib/matplotlib/tests/test_widgets.py::test_rect_visibility[png]", "lib/matplotlib/tests/test_widgets.py::test_rect_visibility[pdf]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_remove[False-1]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_remove[False-2]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_remove[False-3]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_remove[True-1]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_remove[True-2]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_remove[True-3]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_remove_first_point[False]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_remove_first_point[True]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_redraw[False]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_redraw[True]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_verts_setter[png-False]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_verts_setter[png-True]", "lib/matplotlib/tests/test_widgets.py::test_polygon_selector_box", "lib/matplotlib/tests/test_widgets.py::test_MultiCursor[True-True]", "lib/matplotlib/tests/test_widgets.py::test_MultiCursor[True-False]", "lib/matplotlib/tests/test_widgets.py::test_MultiCursor[False-True]"]
de98877e3dc45de8dd441d008f23d88738dc015d
matplotlib/matplotlib
matplotlib__matplotlib-22835
c33557d120eefe3148ebfcf2e758ff2357966000
diff --git a/lib/matplotlib/artist.py b/lib/matplotlib/artist.py --- a/lib/matplotlib/artist.py +++ b/lib/matplotlib/artist.py @@ -12,6 +12,7 @@ import matplotlib as mpl from . import _api, cbook +from .colors import BoundaryNorm from .cm import ScalarMappable from .path import Path from .transforms import (Bbox, IdentityTransform, Transform, TransformedBbox, @@ -1303,10 +1304,20 @@ def format_cursor_data(self, data): return "[]" normed = self.norm(data) if np.isfinite(normed): - # Midpoints of neighboring color intervals. - neighbors = self.norm.inverse( - (int(self.norm(data) * n) + np.array([0, 1])) / n) - delta = abs(neighbors - data).max() + if isinstance(self.norm, BoundaryNorm): + # not an invertible normalization mapping + cur_idx = np.argmin(np.abs(self.norm.boundaries - data)) + neigh_idx = max(0, cur_idx - 1) + # use max diff to prevent delta == 0 + delta = np.diff( + self.norm.boundaries[neigh_idx:cur_idx + 2] + ).max() + + else: + # Midpoints of neighboring color intervals. + neighbors = self.norm.inverse( + (int(normed * n) + np.array([0, 1])) / n) + delta = abs(neighbors - data).max() g_sig_digits = cbook._g_sig_digits(data, delta) else: g_sig_digits = 3 # Consistent with default below.
diff --git a/lib/matplotlib/tests/test_artist.py b/lib/matplotlib/tests/test_artist.py --- a/lib/matplotlib/tests/test_artist.py +++ b/lib/matplotlib/tests/test_artist.py @@ -5,6 +5,8 @@ import pytest +from matplotlib import cm +import matplotlib.colors as mcolors import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.lines as mlines @@ -372,3 +374,164 @@ class MyArtist4(MyArtist3): pass assert MyArtist4.set is MyArtist3.set + + +def test_format_cursor_data_BoundaryNorm(): + """Test if cursor data is correct when using BoundaryNorm.""" + X = np.empty((3, 3)) + X[0, 0] = 0.9 + X[0, 1] = 0.99 + X[0, 2] = 0.999 + X[1, 0] = -1 + X[1, 1] = 0 + X[1, 2] = 1 + X[2, 0] = 0.09 + X[2, 1] = 0.009 + X[2, 2] = 0.0009 + + # map range -1..1 to 0..256 in 0.1 steps + fig, ax = plt.subplots() + fig.suptitle("-1..1 to 0..256 in 0.1") + norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 20), 256) + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + + labels_list = [ + "[0.9]", + "[1.]", + "[1.]", + "[-1.0]", + "[0.0]", + "[1.0]", + "[0.09]", + "[0.009]", + "[0.0009]", + ] + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.1)) + assert img.format_cursor_data(v) == label + + plt.close() + + # map range -1..1 to 0..256 in 0.01 steps + fig, ax = plt.subplots() + fig.suptitle("-1..1 to 0..256 in 0.01") + cmap = cm.get_cmap('RdBu_r', 200) + norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 200), 200) + img = ax.imshow(X, cmap=cmap, norm=norm) + + labels_list = [ + "[0.90]", + "[0.99]", + "[1.0]", + "[-1.00]", + "[0.00]", + "[1.00]", + "[0.09]", + "[0.009]", + "[0.0009]", + ] + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.01)) + assert img.format_cursor_data(v) == label + + plt.close() + + # map range -1..1 to 0..256 in 0.01 steps + fig, ax = plt.subplots() + fig.suptitle("-1..1 to 0..256 in 0.001") + cmap = cm.get_cmap('RdBu_r', 2000) + norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 2000), 2000) + img = ax.imshow(X, cmap=cmap, norm=norm) + + labels_list = [ + "[0.900]", + "[0.990]", + "[0.999]", + "[-1.000]", + "[0.000]", + "[1.000]", + "[0.090]", + "[0.009]", + "[0.0009]", + ] + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.001)) + assert img.format_cursor_data(v) == label + + plt.close() + + # different testing data set with + # out of bounds values for 0..1 range + X = np.empty((7, 1)) + X[0] = -1.0 + X[1] = 0.0 + X[2] = 0.1 + X[3] = 0.5 + X[4] = 0.9 + X[5] = 1.0 + X[6] = 2.0 + + labels_list = [ + "[-1.0]", + "[0.0]", + "[0.1]", + "[0.5]", + "[0.9]", + "[1.0]", + "[2.0]", + ] + + fig, ax = plt.subplots() + fig.suptitle("noclip, neither") + norm = mcolors.BoundaryNorm( + np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='neither') + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33)) + assert img.format_cursor_data(v) == label + + plt.close() + + fig, ax = plt.subplots() + fig.suptitle("noclip, min") + norm = mcolors.BoundaryNorm( + np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='min') + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33)) + assert img.format_cursor_data(v) == label + + plt.close() + + fig, ax = plt.subplots() + fig.suptitle("noclip, max") + norm = mcolors.BoundaryNorm( + np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='max') + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33)) + assert img.format_cursor_data(v) == label + + plt.close() + + fig, ax = plt.subplots() + fig.suptitle("noclip, both") + norm = mcolors.BoundaryNorm( + np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='both') + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33)) + assert img.format_cursor_data(v) == label + + plt.close() + + fig, ax = plt.subplots() + fig.suptitle("clip, neither") + norm = mcolors.BoundaryNorm( + np.linspace(0, 1, 4, endpoint=True), 256, clip=True, extend='neither') + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33)) + assert img.format_cursor_data(v) == label + + plt.close()
# Enhanced Problem Statement: BoundaryNorm cursor data formatting crash ## Issue Description In Matplotlib 3.5.0, when visualizing data with a `BoundaryNorm` normalization, moving the mouse cursor over the image causes the application to crash with a `ValueError: BoundaryNorm is not invertible` exception. This happens because the cursor data formatting functionality attempts to use the `inverse()` method of the normalization object to convert from the normalized color space back to data values. While most normalization classes implement this inverse functionality, `BoundaryNorm` explicitly raises an exception when its `inverse()` method is called, as it maps continuous data to discrete intervals making a true mathematical inverse ambiguous. This exception is not caught by the cursor data handling code, causing the entire interactive functionality to break when users hover over visualizations using `BoundaryNorm`. ## Reproduction Steps ```python import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl fig, ax = plt.subplots() norm = mpl.colors.BoundaryNorm(np.linspace(-4, 4, 5), 256) X = np.random.randn(10, 10) pc = ax.imshow(X, cmap='RdBu_r', norm=norm) plt.show() # When hovering over the image, interaction crashes ``` When you mouse over the image, the following error occurs: ``` File "/Users/jklymak/matplotlib/lib/matplotlib/artist.py", line 1282, in format_cursor_data neighbors = self.norm.inverse( File "/Users/jklymak/matplotlib/lib/matplotlib/colors.py", line 1829, in inverse raise ValueError("BoundaryNorm is not invertible") ValueError: BoundaryNorm is not invertible ``` Internally, what happens: 1. Moving the cursor over the image triggers the tooltip/cursor data display 2. `Artist.format_cursor_data()` is called to format the data value under the cursor 3. For scalar mappables (like images), it attempts to determine appropriate formatting by calculating neighbor values 4. It calls `self.norm.inverse()` to map from normalized color space back to data values 5. `BoundaryNorm.inverse()` raises a `ValueError` rather than returning a value 6. The uncaught exception crashes the interactive functionality ## Expected Behavior When hovering over an image that uses `BoundaryNorm`, the cursor should display useful information about the data value under the cursor without crashing. Either `BoundaryNorm` should provide an approximate inverse operation (perhaps returning the midpoint of the corresponding interval), or the cursor data formatting code should gracefully handle norms that cannot be inverted. ## Exploration Hints ### Files to Examine: - **lib/matplotlib/colors.py** - Contains the `BoundaryNorm` class which raises the exception. The `inverse()` method explicitly raises a `ValueError` with message "BoundaryNorm is not invertible", which is the direct cause of the crash. - **lib/matplotlib/artist.py** - Contains the `format_cursor_data` method that calls `norm.inverse()` without proper error handling, leading to the crash during mouse hover interactions. ### Key Classes/Functions: - **BoundaryNorm.inverse()** - Currently raises `ValueError`. Needs to either implement approximate inverse functionality or be handled differently by callers. - **Artist.format_cursor_data()** - Attempts to use `self.norm.inverse()` without checking if the norm is invertible or handling potential exceptions. - **ScalarMappable** - Base class that connects data values to their visual representation using norms and colormaps. The error happens when formatting cursor data for ScalarMappable objects. ### Areas of Interest: - The norm interface design assumes invertibility, but some norms like `BoundaryNorm` don't satisfy this assumption. - The cursor data formatting code path needs more robust error handling to prevent crashes during interactive use. - The normalization pipeline (data → norm → [0,1] → colormap → RGBA) and how its inverse operations are handled. ## Fix Hints ### High Confidence Locations: - **BoundaryNorm.inverse()** in colors.py - Modify to provide an approximate inverse instead of raising an exception. - **Artist.format_cursor_data()** in artist.py around line 1282 - Add error handling around the call to `self.norm.inverse()`. ### Implementation Hints: 1. **Make BoundaryNorm approximately invertible**: - Implement an inverse that returns the midpoint of the corresponding interval. - This preserves mathematical integrity while providing useful UI feedback. - Challenge: Determining which interval a normalized value belongs to may require additional logic. 2. **Add error handling in format_cursor_data**: - Wrap the call to `self.norm.inverse()` in a try-except block. - Provide a fallback formatting method when inverse fails. - Advantage: Works for any non-invertible norm, not just BoundaryNorm. 3. **Add invertible property to Norm class**: - Let norms declare whether they support inverse operations. - Check this property before attempting inverse operations. - Provides a cleaner architectural solution but requires more extensive changes. ### Alternative Hypotheses: 1. The issue might be part of a larger problem with how matplotlib handles invertible vs non-invertible transformations. There could be other places in the codebase that incorrectly assume all norms are invertible. 2. The cursor data formatting could be delegated to the norm object itself, allowing each norm to determine how to represent its values rather than requiring a strict inverse operation. 3. A regression might have been introduced in 3.5.0 where previous versions handled this case differently or didn't attempt to use the inverse for cursor data formatting with BoundaryNorm.
I think the correct fix is to specifically check for BoundaryNorm there and implement special logic to determine the positions of the neighboring intervals (on the BoundaryNorm) for that case. I tried returning the passed in `value` instead of the exception at https://github.com/matplotlib/matplotlib/blob/b2bb7be4ba343fcec6b1dbbffd7106e6af240221/lib/matplotlib/colors.py#L1829 ```python return value ``` and it seems to work. At least the error is gone and the values displayed in the plot (bottom right) when hovering with the mouse seem also right. But the numbers are rounded to only 1 digit in sci notation. So 19, 20 or 21 become 2.e+01. Hope this helps. Maybe a more constructive suggestion for a change in https://github.com/matplotlib/matplotlib/blob/b2bb7be4ba343fcec6b1dbbffd7106e6af240221/lib/matplotlib/artist.py#L1280 that tries to fix the error: ```python ends = self.norm(np.array([self.norm.vmin, self.norm.vmax])) if np.isfinite(normed) and np.allclose(ends, 0.5, rtol=0.0, atol=0.5): ``` This way, because `BoundaryNorm` doesn't map to 0...1 range but to the indices of the colors, the call to `BoundaryNorm.inverse()` is skipped and the default value for `g_sig_digits=3` is used. But I'm not sure if there can be a case where `BoundaryNorm` actually maps its endpoints to 0...1, in which case all breaks down. hey, I just ran into this while plotting data... (interactivity doesn't stop but it plots a lot of issues) any updates? @raphaelquast no, this still needs someone to work on it. Labeled as a good first issue as there in no API design here (just returning an empty string is better than the current state). I can give a PR, that is based on my [last comment](https://github.com/matplotlib/matplotlib/issues/21915#issuecomment-992454625) a try. But my concerns/questions from then are still valid. As this is all internal code, I think we should just do an `isinstance(norm, BoundaryNorm)` check and then act accordingly. There is already a bunch of instances of this in the colorbar code as precedence. After thinking about my suggestion again, I now understand why you prefer an `isinstace` check. (In my initial suggestion one would have to check if `ends` maps to (0,1) and if `normed` is in [0, 1] for the correct way to implement my idea. But these conditions are taylored to catch `BoundaryNorm` anyway, so why not do it directly.) However, I suggest using a try block after https://github.com/matplotlib/matplotlib/blob/c33557d120eefe3148ebfcf2e758ff2357966000/lib/matplotlib/artist.py#L1305 ```python # Midpoints of neighboring color intervals. try: neighbors = self.norm.inverse( (int(normed * n) + np.array([0, 1])) / n) except ValueError: # non-invertible ScalarMappable ``` because `BoundaryNorm` raises a `ValueError` anyway and I assume this to be the case for all non-invertible `ScalarMappables`. (And the issue is the exception raised from `inverse`). The question is: What to put in the `except`? So what is "acting accordingly" in this case? If `BoundaryNorm` isn't invertible, how can we reliably get the data values of the midpoints of neighboring colors? I think it should be enough to get the boundaries themselves, instead of the midpoints (though both is possible) with something like: ```python cur_idx = np.argmin(np.abs(self.norm.boundaries - data)) cur_bound = self.norm.boundaries[cur_idx] neigh_idx = cur_idx + 1 if data > cur_bound else cur_idx - 1 neighbors = self.norm.boundaries[ np.array([cur_idx, neigh_idx]) ] ``` Problems with this code are: - `boundaries` property is specific to `BoundaryNorm`, isn't it? So we gained nothing by using `try .. except` - more checks are needed to cover all cases for `clip` and `extend` options of `BoundaryNorm` such that `neigh_idx` is always in bounds - for very coarse boundaries compared to data (ie: `boundaries = [0,1,2,3,4,5]; data = random(n)*5) the displayed values are always rounded to one significant digit. While in principle, this is expected (I believe), it results in inconsistency. In my example 0.111111 would be given as 0.1 and 0.001 as 0.001 and 1.234 would be just 1. > boundaries property is specific to BoundaryNorm, isn't it? So we gained nothing by using try .. except This is one argument in favor of doing the `isinstance` check because then you can assert we _have_ a BoundaryNorm and can trust that you can access its state etc. One on hand, duck typeing is in general a Good Thing in Python and we should err on the side of being forgiving on input, but sometimes the complexity of it is more trouble than it is worth if you really only have 1 case that you are trying catch! > I assume this to be the case for all non-invertible ScalarMappables. However we only (at this point) are talking about a way to recover in the case of BoundaryNorm. Let everything else continue to fail and we will deal with those issues if/when they get reported. I think the correct fix is to specifically check for BoundaryNorm there and implement special logic to determine the positions of the neighboring intervals (on the BoundaryNorm) for that case. I tried returning the passed in `value` instead of the exception at https://github.com/matplotlib/matplotlib/blob/b2bb7be4ba343fcec6b1dbbffd7106e6af240221/lib/matplotlib/colors.py#L1829 ```python return value ``` and it seems to work. At least the error is gone and the values displayed in the plot (bottom right) when hovering with the mouse seem also right. But the numbers are rounded to only 1 digit in sci notation. So 19, 20 or 21 become 2.e+01. Hope this helps. Maybe a more constructive suggestion for a change in https://github.com/matplotlib/matplotlib/blob/b2bb7be4ba343fcec6b1dbbffd7106e6af240221/lib/matplotlib/artist.py#L1280 that tries to fix the error: ```python ends = self.norm(np.array([self.norm.vmin, self.norm.vmax])) if np.isfinite(normed) and np.allclose(ends, 0.5, rtol=0.0, atol=0.5): ``` This way, because `BoundaryNorm` doesn't map to 0...1 range but to the indices of the colors, the call to `BoundaryNorm.inverse()` is skipped and the default value for `g_sig_digits=3` is used. But I'm not sure if there can be a case where `BoundaryNorm` actually maps its endpoints to 0...1, in which case all breaks down. hey, I just ran into this while plotting data... (interactivity doesn't stop but it plots a lot of issues) any updates? @raphaelquast no, this still needs someone to work on it. Labeled as a good first issue as there in no API design here (just returning an empty string is better than the current state). I can give a PR, that is based on my [last comment](https://github.com/matplotlib/matplotlib/issues/21915#issuecomment-992454625) a try. But my concerns/questions from then are still valid. As this is all internal code, I think we should just do an `isinstance(norm, BoundaryNorm)` check and then act accordingly. There is already a bunch of instances of this in the colorbar code as precedence. After thinking about my suggestion again, I now understand why you prefer an `isinstace` check. (In my initial suggestion one would have to check if `ends` maps to (0,1) and if `normed` is in [0, 1] for the correct way to implement my idea. But these conditions are taylored to catch `BoundaryNorm` anyway, so why not do it directly.) However, I suggest using a try block after https://github.com/matplotlib/matplotlib/blob/c33557d120eefe3148ebfcf2e758ff2357966000/lib/matplotlib/artist.py#L1305 ```python # Midpoints of neighboring color intervals. try: neighbors = self.norm.inverse( (int(normed * n) + np.array([0, 1])) / n) except ValueError: # non-invertible ScalarMappable ``` because `BoundaryNorm` raises a `ValueError` anyway and I assume this to be the case for all non-invertible `ScalarMappables`. (And the issue is the exception raised from `inverse`). The question is: What to put in the `except`? So what is "acting accordingly" in this case? If `BoundaryNorm` isn't invertible, how can we reliably get the data values of the midpoints of neighboring colors? I think it should be enough to get the boundaries themselves, instead of the midpoints (though both is possible) with something like: ```python cur_idx = np.argmin(np.abs(self.norm.boundaries - data)) cur_bound = self.norm.boundaries[cur_idx] neigh_idx = cur_idx + 1 if data > cur_bound else cur_idx - 1 neighbors = self.norm.boundaries[ np.array([cur_idx, neigh_idx]) ] ``` Problems with this code are: - `boundaries` property is specific to `BoundaryNorm`, isn't it? So we gained nothing by using `try .. except` - more checks are needed to cover all cases for `clip` and `extend` options of `BoundaryNorm` such that `neigh_idx` is always in bounds - for very coarse boundaries compared to data (ie: `boundaries = [0,1,2,3,4,5]; data = random(n)*5) the displayed values are always rounded to one significant digit. While in principle, this is expected (I believe), it results in inconsistency. In my example 0.111111 would be given as 0.1 and 0.001 as 0.001 and 1.234 would be just 1. > boundaries property is specific to BoundaryNorm, isn't it? So we gained nothing by using try .. except This is one argument in favor of doing the `isinstance` check because then you can assert we _have_ a BoundaryNorm and can trust that you can access its state etc. One on hand, duck typeing is in general a Good Thing in Python and we should err on the side of being forgiving on input, but sometimes the complexity of it is more trouble than it is worth if you really only have 1 case that you are trying catch! > I assume this to be the case for all non-invertible ScalarMappables. However we only (at this point) are talking about a way to recover in the case of BoundaryNorm. Let everything else continue to fail and we will deal with those issues if/when they get reported.
2022-04-12T23:13:58Z
3.5
["lib/matplotlib/tests/test_artist.py::test_format_cursor_data_BoundaryNorm"]
["lib/matplotlib/tests/test_artist.py::test_patch_transform_of_none", "lib/matplotlib/tests/test_artist.py::test_collection_transform_of_none", "lib/matplotlib/tests/test_artist.py::test_clipping[png]", "lib/matplotlib/tests/test_artist.py::test_clipping[pdf]", "lib/matplotlib/tests/test_artist.py::test_clipping_zoom[png]", "lib/matplotlib/tests/test_artist.py::test_cull_markers", "lib/matplotlib/tests/test_artist.py::test_hatching[png]", "lib/matplotlib/tests/test_artist.py::test_hatching[pdf]", "lib/matplotlib/tests/test_artist.py::test_remove", "lib/matplotlib/tests/test_artist.py::test_default_edges[png]", "lib/matplotlib/tests/test_artist.py::test_properties", "lib/matplotlib/tests/test_artist.py::test_setp", "lib/matplotlib/tests/test_artist.py::test_None_zorder", "lib/matplotlib/tests/test_artist.py::test_artist_inspector_get_valid_values[-unknown]", "lib/matplotlib/tests/test_artist.py::test_artist_inspector_get_valid_values[ACCEPTS:", "lib/matplotlib/tests/test_artist.py::test_artist_inspector_get_valid_values[..", "lib/matplotlib/tests/test_artist.py::test_artist_inspector_get_valid_values[arg", "lib/matplotlib/tests/test_artist.py::test_artist_inspector_get_valid_values[*arg", "lib/matplotlib/tests/test_artist.py::test_artist_inspector_get_aliases", "lib/matplotlib/tests/test_artist.py::test_set_alpha", "lib/matplotlib/tests/test_artist.py::test_set_alpha_for_array", "lib/matplotlib/tests/test_artist.py::test_callbacks", "lib/matplotlib/tests/test_artist.py::test_set_signature", "lib/matplotlib/tests/test_artist.py::test_set_is_overwritten"]
de98877e3dc45de8dd441d008f23d88738dc015d
pallets/flask
pallets__flask-4992
4c288bc97ea371817199908d0d9b12de9dae327e
diff --git a/src/flask/config.py b/src/flask/config.py --- a/src/flask/config.py +++ b/src/flask/config.py @@ -234,6 +234,7 @@ def from_file( filename: str, load: t.Callable[[t.IO[t.Any]], t.Mapping], silent: bool = False, + text: bool = True, ) -> bool: """Update the values in the config from a file that is loaded using the ``load`` parameter. The loaded data is passed to the @@ -244,8 +245,8 @@ def from_file( import json app.config.from_file("config.json", load=json.load) - import toml - app.config.from_file("config.toml", load=toml.load) + import tomllib + app.config.from_file("config.toml", load=tomllib.load, text=False) :param filename: The path to the data file. This can be an absolute path or relative to the config root path. @@ -254,14 +255,18 @@ def from_file( :type load: ``Callable[[Reader], Mapping]`` where ``Reader`` implements a ``read`` method. :param silent: Ignore the file if it doesn't exist. + :param text: Open the file in text or binary mode. :return: ``True`` if the file was loaded successfully. + .. versionchanged:: 2.3 + The ``text`` parameter was added. + .. versionadded:: 2.0 """ filename = os.path.join(self.root_path, filename) try: - with open(filename) as f: + with open(filename, "r" if text else "rb") as f: obj = load(f) except OSError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR):
diff --git a/tests/static/config.toml b/tests/static/config.toml new file mode 100644 --- /dev/null +++ b/tests/static/config.toml @@ -0,0 +1,2 @@ +TEST_KEY="foo" +SECRET_KEY="config" diff --git a/tests/test_config.py b/tests/test_config.py --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,7 +6,6 @@ import flask - # config keys used for the TestConfig TEST_KEY = "foo" SECRET_KEY = "config" @@ -30,13 +29,23 @@ def test_config_from_object(): common_object_test(app) -def test_config_from_file(): +def test_config_from_file_json(): app = flask.Flask(__name__) current_dir = os.path.dirname(os.path.abspath(__file__)) app.config.from_file(os.path.join(current_dir, "static", "config.json"), json.load) common_object_test(app) +def test_config_from_file_toml(): + tomllib = pytest.importorskip("tomllib", reason="tomllib added in 3.11") + app = flask.Flask(__name__) + current_dir = os.path.dirname(os.path.abspath(__file__)) + app.config.from_file( + os.path.join(current_dir, "static", "config.toml"), tomllib.load, text=False + ) + common_object_test(app) + + def test_from_prefixed_env(monkeypatch): monkeypatch.setenv("FLASK_STRING", "value") monkeypatch.setenv("FLASK_BOOL", "true")
# Enhanced Problem Statement: Adding File Mode Parameter to Flask Config.from_file() ## Issue Description Flask's `Config.from_file()` method currently only opens files in text mode, making it incompatible with Python 3.11's native TOML support via the `tomllib` module. The `tomllib.load()` function requires files to be opened in binary mode (`'rb'`), but `Config.from_file()` has no parameter to specify the file opening mode. This creates a compatibility issue that forces developers to use more verbose workarounds when loading TOML configuration files with the native `tomllib` module. The problem occurs specifically when trying to use the elegant `app.config.from_file("config.toml", tomllib.load)` syntax, which results in a TypeError because of the mode mismatch. ## Reproduction Steps 1. Install Flask and use Python 3.11 which includes the native `tomllib` module 2. Create a TOML configuration file (e.g., `config.toml`) 3. Attempt to load the file using: ```python app.config.from_file("config.toml", tomllib.load) ``` 4. Observe the following error: ``` TypeError: File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')` ``` The error occurs because internally, `Config.from_file()` opens files using `open(filename)` without specifying a mode, which defaults to text mode (`'r'`). Meanwhile, `tomllib.load()` expects a file opened in binary mode. Currently, developers must work around this limitation by: ```python # Manual workaround requiring path joining logic that from_file() normally handles with open(os.path.join(app.config.root_path, "config.toml"), "rb") as file: app.config.from_mapping(tomllib.load(file)) ``` ## Expected Behavior `Config.from_file()` should accept an optional `mode` parameter that defaults to `'r'` (text mode) for backward compatibility, but allows users to specify `'rb'` (binary mode) or other file modes as needed. This would enable simple and elegant configuration loading with Python's native TOML support: ```python app.config.from_file("config.toml", tomllib.load, mode="rb") ``` ## Exploration Hints ### Files to Examine: - **src/flask/config.py** - Contains the `Config` class with the `from_file()` method that needs modification. This file manages Flask's configuration system and handles all config loading operations, including the file opening mechanism that currently doesn't support binary mode. ### Key Classes/Functions: - **Config.from_file()** - This method needs modification to accept a file mode parameter. Currently, it opens files with `open(filename)` (defaulting to text mode), calls the provided loader function with the file object, and updates the configuration with the resulting dictionary. - **Config.from_mapping()** - Used in the current workaround solution; this method is an alternative way to update the configuration when direct file loading doesn't work. ### Areas of Interest: - The `from_file()` method follows Flask's common pattern of accepting callable processors for operations, in this case a loader function that processes file content. - The method handles path joining (combining the app's root path with relative filenames), which is why the workaround is more verbose and requires manual path handling. - Flask configuration loading typically provides sensible defaults while allowing customization, so any change should maintain backward compatibility. ## Fix Hints ### High Confidence Locations: - **Config.from_file()** method signature and implementation in src/flask/config.py - The method needs to be updated to accept an optional `mode` parameter and use it when opening files. ### Implementation Hints: 1. Add a `mode` parameter to the method signature with a default value of `'r'` to maintain backward compatibility. 2. Modify the file opening line to use this parameter: `with open(filename, mode) as f:`. 3. Update the method's type annotation and docstring to document the new parameter. 4. Add examples in the docstring showing usage with `tomllib.load` and binary mode. Sample implementation: ```python def from_file( self, filename: str, load: t.Callable[[t.IO[t.Any]], t.Mapping], mode: str = "r", silent: bool = False ) -> bool: """Update the values in the config from a file that is loaded using the ``load`` parameter. The loaded data is passed to the :meth:`from_mapping` method. ... :param mode: The file mode to use when opening the file. Defaults to 'r' (text mode). Use 'rb' for binary mode, required by some loaders like Python 3.11's tomllib.load. ... Example of loading using Python 3.11's native TOML support:: app.config.from_file("config.toml", tomllib.load, mode="rb") """ # implementation with updated open() call using the mode parameter ``` ### Alternative Hypotheses: 1. **Create a new method**: Instead of modifying `from_file()`, a new method like `from_binary_file()` could be added specifically for binary formats. However, this would increase API surface area and potential confusion. 2. **Wrapper function approach**: A helper function could be provided that wraps loaders requiring binary mode. This would avoid changing the API but requires more code on the user's side. 3. **Automatic mode detection**: The method could attempt to inspect the loader function to determine if it requires binary mode, but this would be complex and potentially unreliable. 4. **Change default behavior**: In a major version update, Flask could change the default behavior to open files in binary mode, but this would break backward compatibility with loaders that expect text mode. The proposed solution (adding an optional `mode` parameter) offers the best balance of simplicity, backward compatibility, and addressing the immediate need to support Python's native TOML library.
You can also use: ```python app.config.from_file("config.toml", lambda f: tomllib.load(f.buffer)) ``` Thanks - I was looking for another way to do it. I'm happy with that for now, although it's worth noting this about `io.TextIOBase.buffer` from the docs: > This is not part of the [TextIOBase](https://docs.python.org/3/library/io.html#io.TextIOBase) API and may not exist in some implementations. Oh, didn't mean for you to close this, that was just a shorter workaround. I think a `text=True` parameter would be better, easier to use `True` or `False` rather than mode strings. Some libraries, like `tomllib`, have _Opinions_ about whether text or bytes are correct for parsing files, and we can accommodate that. can i work on this? No need to ask to work on an issue. As long as the issue is not assigned to anyone and doesn't have have a linked open PR (both can be seen in the sidebar), anyone is welcome to work on any issue.
2023-02-22T14:00:17Z
2.3
["tests/test_config.py::test_config_from_file_toml"]
["tests/test_config.py::test_config_from_pyfile", "tests/test_config.py::test_config_from_object", "tests/test_config.py::test_config_from_file_json", "tests/test_config.py::test_from_prefixed_env", "tests/test_config.py::test_from_prefixed_env_custom_prefix", "tests/test_config.py::test_from_prefixed_env_nested", "tests/test_config.py::test_config_from_mapping", "tests/test_config.py::test_config_from_class", "tests/test_config.py::test_config_from_envvar", "tests/test_config.py::test_config_from_envvar_missing", "tests/test_config.py::test_config_missing", "tests/test_config.py::test_config_missing_file", "tests/test_config.py::test_custom_config_class", "tests/test_config.py::test_session_lifetime", "tests/test_config.py::test_get_namespace", "tests/test_config.py::test_from_pyfile_weird_encoding[utf-8]", "tests/test_config.py::test_from_pyfile_weird_encoding[iso-8859-15]", "tests/test_config.py::test_from_pyfile_weird_encoding[latin-1]"]
182ce3dd15dfa3537391c3efaf9c3ff407d134d4
matplotlib/matplotlib
matplotlib__matplotlib-25433
7eafdd8af3c523c1c77b027d378fb337dd489f18
diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -931,6 +931,7 @@ def _break_share_link(ax, grouper): self._axobservers.process("_axes_change_event", self) self.stale = True self._localaxes.remove(ax) + self.canvas.release_mouse(ax) # Break link between any shared axes for name in ax._axis_names:
diff --git a/lib/matplotlib/tests/test_backend_bases.py b/lib/matplotlib/tests/test_backend_bases.py --- a/lib/matplotlib/tests/test_backend_bases.py +++ b/lib/matplotlib/tests/test_backend_bases.py @@ -95,6 +95,16 @@ def test_non_gui_warning(monkeypatch): in str(rec[0].message)) +def test_grab_clear(): + fig, ax = plt.subplots() + + fig.canvas.grab_mouse(ax) + assert fig.canvas.mouse_grabber == ax + + fig.clear() + assert fig.canvas.mouse_grabber is None + + @pytest.mark.parametrize( "x, y", [(42, 24), (None, 42), (None, None), (200, 100.01), (205.75, 2.0)]) def test_location_event_position(x, y):
# Enhanced Problem Statement: RangeSlider Input Blocking After Redrawing in on_changed Callback ## Issue Description There is a specific bug in matplotlib's `RangeSlider` widget where using `pyplot.clf()` followed by `pyplot.draw()` within the `on_changed` callback blocks all further input to widgets in the figure. This behavior is inconsistent with the `Button` widget, which continues to work correctly when the same operations are performed in its `on_clicked` callback. The issue occurs on both Windows and Linux systems with different matplotlib backends (TkAgg, QtAgg), suggesting it's a core problem in how the `RangeSlider` handles event management rather than a platform-specific issue. The root cause likely involves how mouse events are grabbed and released during slider interaction, and how widget event connections are maintained when clearing and redrawing figures. ## Reproduction Steps ```python import matplotlib.pyplot as pyplot import matplotlib.widgets as widgets def onchanged(values): print("on changed") print(values) pyplot.clf() addElements() pyplot.draw() def onclick(e): print("on click") pyplot.clf() addElements() pyplot.draw() def addElements(): ax = pyplot.axes([0.1, 0.45, 0.8, 0.1]) global slider slider = widgets.RangeSlider(ax, "Test", valmin=1, valmax=10, valinit=(1, 10)) slider.on_changed(onchanged) ax = pyplot.axes([0.1, 0.30, 0.8, 0.1]) global button button = widgets.Button(ax, "Test") button.on_clicked(onclick) addElements() pyplot.show() ``` When running this code: 1. Moving the RangeSlider triggers the `onchanged` callback 2. Inside the callback, the figure is cleared, new elements are added, and the figure is redrawn 3. After this operation, no widgets in the figure respond to mouse clicks or interactions 4. However, clicking the Button widget works properly - it triggers `onclick`, clears/redraws the figure, and widgets remain responsive What appears to happen internally: - When a slider is moved, the canvas mouse events are "grabbed" by the slider - For the `Button` widget, mouse events are released in the `_release()` method after a click - For the `RangeSlider`, the mouse events may not be properly released when clearing the figure during an active slider callback ## Expected Behavior The `RangeSlider.on_changed` callback should behave consistently with the `Button.on_clicked` callback. After clearing and redrawing the figure within the callback, all widgets should remain responsive to user input. The issue should not occur regardless of which widget's callback initiated the clear-and-redraw operation. ## Exploration Hints ### Files to Examine: - **lib/matplotlib/widgets.py** - Contains the implementation of both `RangeSlider` and `Button` widgets. The key differences in event handling between these widgets are the source of the bug. - **lib/matplotlib/backends/backend_agg.py** - May contain relevant canvas event handling code for the TkAgg backend. - **lib/matplotlib/pyplot.py** - Contains the implementation of `clf()` and `draw()` functions, which might affect how widget connections are maintained. ### Key Classes/Functions: - **RangeSlider.on_changed()** - How this registers callbacks and manages event handling differs from Button.on_clicked() - **SliderBase._active** - May track the active state of sliders which could affect event grabbing/releasing - **Button._release()** - Contains code for properly releasing mouse events after button interaction - **canvas.grab_mouse()** / **canvas.release_mouse()** - Functions used to control mouse event routing - **pyplot.clf()** - How figure clearing affects widget event connections ### Areas of Interest: - Mouse event handling in `SliderBase` and its subclasses - How canvas mouse grabbing/releasing works during widget interactions - Event connection cleanup when figures are cleared - Differences between how button clicks and slider dragging events are processed - Timing of event processing relative to figure clearing and redrawing ## Fix Hints ### High Confidence Locations: - `RangeSlider` class or its parent `SliderBase` in widgets.py - The issue is almost certainly in how these classes handle mouse events and release them after interaction - The mouse event handling code for sliders needs to properly release mouse grabs when a figure is cleared during callback execution ### Implementation Hints: - Compare how `Button._release()` releases mouse events versus how `RangeSlider` handles its mouse release - Consider adding a check in `RangeSlider`'s event handlers to ensure `release_mouse()` is called before or after figure clearing - Examine whether `canvas.mouse_grabber` is properly reset after slider interactions - A possible fix could involve ensuring that any mouse grab is released before executing the callback that might clear the figure - Consider implementing a cleanup method that's called when widgets are destroyed during figure clearing ### Alternative Hypotheses: 1. The issue could be in how matplotlib's event processing queue handles events during redrawing - if the slider callback clears the figure while event handling is still in progress, it might corrupt the event system state 2. There might be a timing or race condition where the figure clearing happens while the slider is still considered "active" 3. The problem could be in how event connections are re-established after the figure is redrawn - perhaps button events are reconnected properly but slider events aren't 4. The slider widget might be maintaining internal state that becomes invalid after a figure clear operation 5. Different widget types might use different event connection mechanisms under the hood, leading to inconsistent behavior when the figure is cleared
A can confirm this behavior, but removing and recreating the objects that host the callbacks in the callbacks is definitely on the edge of the intended usage. Why are you doing this? In your application can you get away with not destroying your slider? I think there could be a way to not destroy the slider. But I don't have the time to test that currently. My workaround for the problem was using a button to redraw everything. With that everything is working fine. That was the weird part for me as they are both callbacks, but in one everything works fine and in the other one all inputs are blocked. If what I'm trying doing is not the intended usage, that's fine for me. Thanks for the answer. The idiomatic way to destructively work on widgets that triggered an event in a UI toolkit is to do the destructive work in an idle callback: ```python def redraw(): pyplot.clf() addElements() pyplot.draw() return False def onchanged(values): print("on changed") print(values) pyplot.gcf().canvas.new_timer(redraw) ``` Thanks for the answer. I tried that with the code in the original post. The line: ```python pyplot.gcf().canvas.new_timer(redraw) ``` doesn't work for me. After having a look at the documentation, I think the line should be: ```python pyplot.gcf().canvas.new_timer(callbacks=[(redraw, tuple(), dict())]) ``` But that still didn't work. The redraw callback doesn't seem to trigger. Sorry, I mean to update that after testing and before posting, but forgot to. That line should be: ``` pyplot.gcf().canvas.new_timer(callbacks=[redraw]) ``` Sorry for double posting; now I see that it didn't actually get called! That's because I forgot to call `start` as well, and the timer was garbage collected at the end of the function. It should be called as you've said, but stored globally and started: ``` import matplotlib.pyplot as pyplot import matplotlib.widgets as widgets def redraw(): print("redraw") pyplot.clf() addElements() pyplot.draw() return False def onchanged(values): print("on changed") print(values) global timer timer = pyplot.gcf().canvas.new_timer(callbacks=[(redraw, (), {})]) timer.start() def onclick(e): print("on click") global timer timer = pyplot.gcf().canvas.new_timer(callbacks=[(redraw, (), {})]) timer.start() def addElements(): ax = pyplot.axes([0.1, 0.45, 0.8, 0.1]) global slider slider = widgets.RangeSlider(ax, "Test", valmin=1, valmax=10, valinit=(1, 10)) slider.on_changed(onchanged) ax = pyplot.axes([0.1, 0.30, 0.8, 0.1]) global button button = widgets.Button(ax, "Test") button.on_clicked(onclick) addElements() pyplot.show() ``` Thanks for the answer, the code works without errors, but I'm still able to break it when using the range slider. Then it results in the same problem as my original post. It seems like that happens when triggering the onchanged callback at the same time the timer callback gets called. Are you sure it's not working, or is it just that it got replaced by a new one that is using the same initial value again? For me, it moves, but once the callback runs, it's reset because the slider is created with `valinit=(1, 10)`. The code redraws everything fine, but when the onchanged callback of the range slider gets called at the same time as the redraw callback of the timer, I'm not able to give any new inputs to the widgets. You can maybe reproduce that with changing the value of the slider the whole time, while waiting for the redraw. I think what is happening is that because you are destroying the slider every time the you are also destroying the state of what value you changed it to. When you create it you re-create it at the default value which produces the effect that you can not seem to change it. Put another way, the state of what the current value of the slider is is in the `Slider` object. Replacing the slider object with a new one (correctly) forgets the old value. ----- I agree it fails in surprising ways, but I think that this is best case "undefined behavior" and worst case incorrect usage of the tools. In either case there is not much we can do upstream to address this (as if the user _did_ want to get fresh sliders that is not a case we should prevent from happening or warn on). The "forgetting the value" is not the problem. My problem is, that the input just blocks for every widget in the figure. When that happens, you can click on any widget, but no callback gets triggered. That problem seems to happen when a callback of an object gets called that is/has been destroyed, but I don't know for sure. But if that is from the incorrect usage of the tools, that's fine for me. I got a decent workaround that works currently, so I just have to keep that in my code for now.
2023-03-11T08:36:32Z
3.7
["lib/matplotlib/tests/test_backend_bases.py::test_grab_clear"]
["lib/matplotlib/tests/test_backend_bases.py::test_uses_per_path", "lib/matplotlib/tests/test_backend_bases.py::test_canvas_ctor", "lib/matplotlib/tests/test_backend_bases.py::test_get_default_filename", "lib/matplotlib/tests/test_backend_bases.py::test_canvas_change", "lib/matplotlib/tests/test_backend_bases.py::test_non_gui_warning", "lib/matplotlib/tests/test_backend_bases.py::test_location_event_position[42-24]", "lib/matplotlib/tests/test_backend_bases.py::test_location_event_position[None-42]", "lib/matplotlib/tests/test_backend_bases.py::test_location_event_position[None-None]", "lib/matplotlib/tests/test_backend_bases.py::test_location_event_position[200-100.01]", "lib/matplotlib/tests/test_backend_bases.py::test_location_event_position[205.75-2.0]", "lib/matplotlib/tests/test_backend_bases.py::test_pick", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_zoom", "lib/matplotlib/tests/test_backend_bases.py::test_widgetlock_zoompan", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[zoom-1-expected0-vertical-imshow]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[zoom-1-expected0-vertical-contourf]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[zoom-1-expected0-horizontal-imshow]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[zoom-1-expected0-horizontal-contourf]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[zoom-3-expected1-vertical-imshow]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[zoom-3-expected1-vertical-contourf]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[zoom-3-expected1-horizontal-imshow]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[zoom-3-expected1-horizontal-contourf]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[pan-1-expected2-vertical-imshow]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[pan-1-expected2-vertical-contourf]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[pan-1-expected2-horizontal-imshow]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[pan-1-expected2-horizontal-contourf]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[pan-3-expected3-vertical-imshow]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[pan-3-expected3-vertical-contourf]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[pan-3-expected3-horizontal-imshow]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_colorbar[pan-3-expected3-horizontal-contourf]", "lib/matplotlib/tests/test_backend_bases.py::test_toolbar_zoompan", "lib/matplotlib/tests/test_backend_bases.py::test_draw[svg]", "lib/matplotlib/tests/test_backend_bases.py::test_draw[ps]", "lib/matplotlib/tests/test_backend_bases.py::test_draw[pdf]", "lib/matplotlib/tests/test_backend_bases.py::test_draw[pgf]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[None-mouseend0-expectedxlim0-expectedylim0]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[None-mouseend1-expectedxlim1-expectedylim1]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[None-mouseend2-expectedxlim2-expectedylim2]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[None-mouseend3-expectedxlim3-expectedylim3]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[None-mouseend4-expectedxlim4-expectedylim4]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[None-mouseend5-expectedxlim5-expectedylim5]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[None-mouseend6-expectedxlim6-expectedylim6]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[None-mouseend7-expectedxlim7-expectedylim7]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[shift-mouseend8-expectedxlim8-expectedylim8]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[shift-mouseend9-expectedxlim9-expectedylim9]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[shift-mouseend10-expectedxlim10-expectedylim10]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[shift-mouseend11-expectedxlim11-expectedylim11]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[shift-mouseend12-expectedxlim12-expectedylim12]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[shift-mouseend13-expectedxlim13-expectedylim13]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[x-mouseend14-expectedxlim14-expectedylim14]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[y-mouseend15-expectedxlim15-expectedylim15]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[control-mouseend16-expectedxlim16-expectedylim16]", "lib/matplotlib/tests/test_backend_bases.py::test_interactive_pan[control-mouseend17-expectedxlim17-expectedylim17]", "lib/matplotlib/tests/test_backend_bases.py::test_toolmanager_remove", "lib/matplotlib/tests/test_backend_bases.py::test_toolmanager_get_tool", "lib/matplotlib/tests/test_backend_bases.py::test_toolmanager_update_keymap"]
0849036fd992a2dd133a0cffc3f84f58ccf1840f
pytest-dev/pytest
pytest-dev__pytest-6116
e670ff76cbad80108bde9bab616b66771b8653cf
diff --git a/src/_pytest/main.py b/src/_pytest/main.py --- a/src/_pytest/main.py +++ b/src/_pytest/main.py @@ -109,6 +109,7 @@ def pytest_addoption(parser): group.addoption( "--collectonly", "--collect-only", + "--co", action="store_true", help="only collect tests, don't execute them.", ),
diff --git a/testing/test_collection.py b/testing/test_collection.py --- a/testing/test_collection.py +++ b/testing/test_collection.py @@ -402,7 +402,7 @@ def pytest_collect_file(path, parent): ) testdir.mkdir("sub") testdir.makepyfile("def test_x(): pass") - result = testdir.runpytest("--collect-only") + result = testdir.runpytest("--co") result.stdout.fnmatch_lines(["*MyModule*", "*test_x*"]) def test_pytest_collect_file_from_sister_dir(self, testdir): @@ -433,7 +433,7 @@ def pytest_collect_file(path, parent): p = testdir.makepyfile("def test_x(): pass") p.copy(sub1.join(p.basename)) p.copy(sub2.join(p.basename)) - result = testdir.runpytest("--collect-only") + result = testdir.runpytest("--co") result.stdout.fnmatch_lines(["*MyModule1*", "*MyModule2*", "*test_x*"])
pytest --collect-only needs a one char shortcut command I find myself needing to run `--collect-only` very often and that cli argument is a very long to type one. I do think that it would be great to allocate a character for it, not sure which one yet. Please use up/down thumbs to vote if you would find it useful or not and eventually proposing which char should be used. Clearly this is a change very easy to implement but first I want to see if others would find it useful or not. pytest --collect-only needs a one char shortcut command I find myself needing to run `--collect-only` very often and that cli argument is a very long to type one. I do think that it would be great to allocate a character for it, not sure which one yet. Please use up/down thumbs to vote if you would find it useful or not and eventually proposing which char should be used. Clearly this is a change very easy to implement but first I want to see if others would find it useful or not.
Agreed, it's probably the option I use most which doesn't have a shortcut. Both `-c` and `-o` are taken. I guess `-n` (as in "no action", compare `-n`/`--dry-run` for e.g. `git clean`) could work? Maybe `--co` (for either "**co**llect" or "**c**ollect **o**nly), similar to other two-character shortcuts we already have (`--sw`, `--lf`, `--ff`, `--nf`)? I like `--co`, and it doesn't seem to be used by any plugins as far as I can search: https://github.com/search?utf8=%E2%9C%93&q=--co+language%3APython+pytest+language%3APython+language%3APython&type=Code&ref=advsearch&l=Python&l=Python > I find myself needing to run `--collect-only` very often and that cli argument is a very long to type one. Just out of curiosity: Why? (i.e. what's your use case?) +0 for `--co`. But in general you can easily also have an alias "alias pco='pytest --collect-only'" - (or "alias pco='p --collect-only" if you have a shortcut for pytest already.. :)) I routinely use `--collect-only` when I switch to a different development branch or start working on a different area of our code base. I think `--co` is fine. Agreed, it's probably the option I use most which doesn't have a shortcut. Both `-c` and `-o` are taken. I guess `-n` (as in "no action", compare `-n`/`--dry-run` for e.g. `git clean`) could work? Maybe `--co` (for either "**co**llect" or "**c**ollect **o**nly), similar to other two-character shortcuts we already have (`--sw`, `--lf`, `--ff`, `--nf`)? I like `--co`, and it doesn't seem to be used by any plugins as far as I can search: https://github.com/search?utf8=%E2%9C%93&q=--co+language%3APython+pytest+language%3APython+language%3APython&type=Code&ref=advsearch&l=Python&l=Python > I find myself needing to run `--collect-only` very often and that cli argument is a very long to type one. Just out of curiosity: Why? (i.e. what's your use case?) +0 for `--co`. But in general you can easily also have an alias "alias pco='pytest --collect-only'" - (or "alias pco='p --collect-only" if you have a shortcut for pytest already.. :)) I routinely use `--collect-only` when I switch to a different development branch or start working on a different area of our code base. I think `--co` is fine.
2019-11-01T20:05:53Z
5.2
["testing/test_collection.py::TestCustomConftests::test_pytest_fs_collect_hooks_are_seen", "testing/test_collection.py::TestCustomConftests::test_pytest_collect_file_from_sister_dir"]
["testing/test_collection.py::TestCollector::test_collect_versus_item", "testing/test_collection.py::TestCollector::test_check_equality", "testing/test_collection.py::TestCollector::test_getparent", "testing/test_collection.py::TestCollector::test_getcustomfile_roundtrip", "testing/test_collection.py::TestCollector::test_can_skip_class_with_test_attr", "testing/test_collection.py::TestCollectFS::test_ignored_certain_directories", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs[activate]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs[activate.csh]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs[activate.fish]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs[Activate]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs[Activate.bat]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs[Activate.ps1]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs_norecursedirs_precedence[activate]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs_norecursedirs_precedence[activate.csh]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs_norecursedirs_precedence[activate.fish]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs_norecursedirs_precedence[Activate]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs_norecursedirs_precedence[Activate.bat]", "testing/test_collection.py::TestCollectFS::test_ignored_virtualenvs_norecursedirs_precedence[Activate.ps1]", "testing/test_collection.py::TestCollectFS::test__in_venv[activate]", "testing/test_collection.py::TestCollectFS::test__in_venv[activate.csh]", "testing/test_collection.py::TestCollectFS::test__in_venv[activate.fish]", "testing/test_collection.py::TestCollectFS::test__in_venv[Activate]", "testing/test_collection.py::TestCollectFS::test__in_venv[Activate.bat]", "testing/test_collection.py::TestCollectFS::test__in_venv[Activate.ps1]", "testing/test_collection.py::TestCollectFS::test_custom_norecursedirs", "testing/test_collection.py::TestCollectFS::test_testpaths_ini", "testing/test_collection.py::TestCollectPluginHookRelay::test_pytest_collect_file", "testing/test_collection.py::TestCollectPluginHookRelay::test_pytest_collect_directory", "testing/test_collection.py::TestPrunetraceback::test_custom_repr_failure", "testing/test_collection.py::TestCustomConftests::test_ignore_collect_path", "testing/test_collection.py::TestCustomConftests::test_ignore_collect_not_called_on_argument", "testing/test_collection.py::TestCustomConftests::test_collectignore_exclude_on_option", "testing/test_collection.py::TestCustomConftests::test_collectignoreglob_exclude_on_option", "testing/test_collection.py::TestSession::test_parsearg", "testing/test_collection.py::TestSession::test_collect_topdir", "testing/test_collection.py::TestSession::test_collect_protocol_single_function", "testing/test_collection.py::TestSession::test_collect_protocol_method", "testing/test_collection.py::TestSession::test_collect_custom_nodes_multi_id", "testing/test_collection.py::TestSession::test_collect_subdir_event_ordering", "testing/test_collection.py::TestSession::test_collect_two_commandline_args", "testing/test_collection.py::TestSession::test_serialization_byid", "testing/test_collection.py::TestSession::test_find_byid_without_instance_parents", "testing/test_collection.py::Test_getinitialnodes::test_global_file", "testing/test_collection.py::Test_getinitialnodes::test_pkgfile", "testing/test_collection.py::Test_genitems::test_check_collect_hashes", "testing/test_collection.py::Test_genitems::test_example_items1", "testing/test_collection.py::Test_genitems::test_class_and_functions_discovery_using_glob", "testing/test_collection.py::test_matchnodes_two_collections_same_file", "testing/test_collection.py::TestNodekeywords::test_no_under", "testing/test_collection.py::TestNodekeywords::test_issue345", "testing/test_collection.py::test_exit_on_collection_error", "testing/test_collection.py::test_exit_on_collection_with_maxfail_smaller_than_n_errors", "testing/test_collection.py::test_exit_on_collection_with_maxfail_bigger_than_n_errors", "testing/test_collection.py::test_continue_on_collection_errors", "testing/test_collection.py::test_continue_on_collection_errors_maxfail", "testing/test_collection.py::test_fixture_scope_sibling_conftests", "testing/test_collection.py::test_collect_init_tests", "testing/test_collection.py::test_collect_invalid_signature_message", "testing/test_collection.py::test_collect_handles_raising_on_dunder_class", "testing/test_collection.py::test_collect_with_chdir_during_import", "testing/test_collection.py::test_collect_symlink_file_arg", "testing/test_collection.py::test_collect_symlink_out_of_tree", "testing/test_collection.py::test_collectignore_via_conftest", "testing/test_collection.py::test_collect_pkg_init_and_file_in_args", "testing/test_collection.py::test_collect_pkg_init_only", "testing/test_collection.py::test_collect_sub_with_symlinks[True]", "testing/test_collection.py::test_collect_sub_with_symlinks[False]", "testing/test_collection.py::test_collector_respects_tbstyle", "testing/test_collection.py::test_collect_pyargs_with_testpaths"]
f36ea240fe3579f945bf5d6cc41b5e45a572249d
pytest-dev/pytest
pytest-dev__pytest-7220
56bf819c2f4eaf8b36bd8c42c06bb59d5a3bfc0f
diff --git a/src/_pytest/nodes.py b/src/_pytest/nodes.py --- a/src/_pytest/nodes.py +++ b/src/_pytest/nodes.py @@ -29,6 +29,7 @@ from _pytest.mark.structures import MarkDecorator from _pytest.mark.structures import NodeKeywords from _pytest.outcomes import fail +from _pytest.pathlib import Path from _pytest.store import Store if TYPE_CHECKING: @@ -361,9 +362,14 @@ def _repr_failure_py( else: truncate_locals = True + # excinfo.getrepr() formats paths relative to the CWD if `abspath` is False. + # It is possible for a fixture/test to change the CWD while this code runs, which + # would then result in the user seeing confusing paths in the failure message. + # To fix this, if the CWD changed, always display the full absolute path. + # It will be better to just always display paths relative to invocation_dir, but + # this requires a lot of plumbing (#6428). try: - os.getcwd() - abspath = False + abspath = Path(os.getcwd()) != Path(self.config.invocation_dir) except OSError: abspath = True
diff --git a/testing/test_nodes.py b/testing/test_nodes.py --- a/testing/test_nodes.py +++ b/testing/test_nodes.py @@ -58,3 +58,30 @@ class FakeSession: outside = py.path.local("/outside") assert nodes._check_initialpaths_for_relpath(FakeSession, outside) is None + + +def test_failure_with_changed_cwd(testdir): + """ + Test failure lines should use absolute paths if cwd has changed since + invocation, so the path is correct (#6428). + """ + p = testdir.makepyfile( + """ + import os + import pytest + + @pytest.fixture + def private_dir(): + out_dir = 'ddd' + os.mkdir(out_dir) + old_dir = os.getcwd() + os.chdir(out_dir) + yield out_dir + os.chdir(old_dir) + + def test_show_wrong_path(private_dir): + assert False + """ + ) + result = testdir.runpytest() + result.stdout.fnmatch_lines([str(p) + ":*: AssertionError", "*1 failed in *"])
Wrong path to test file when directory changed in fixture Files are shown as relative to new directory when working directory is changed in a fixture. This makes it impossible to jump to the error as the editor is unaware of the directory change. The displayed directory should stay relative to the original directory. test_path_error.py: ```python import os import errno import shutil import pytest @pytest.fixture def private_dir(): # or (monkeypatch) out_dir = 'ddd' try: shutil.rmtree(out_dir) except OSError as ex: if ex.errno != errno.ENOENT: raise os.mkdir(out_dir) old_dir = os.getcwd() os.chdir(out_dir) yield out_dir os.chdir(old_dir) # Same issue if using: # monkeypatch.chdir(out_dir) def test_show_wrong_path(private_dir): assert False ``` ```diff + Expected: test_path_error.py:29: AssertionError - Displayed: ../test_path_error.py:29: AssertionError ``` The full output is: ``` -*- mode: compilation; default-directory: "~/src/pytest_path_error/" -*- Compilation started at Fri Jan 10 00:05:52 nox nox > Running session test nox > Creating virtual environment (virtualenv) using python3.7 in .nox/test nox > pip install pytest>=5.3 nox > pip freeze attrs==19.3.0 importlib-metadata==1.3.0 more-itertools==8.0.2 packaging==20.0 pluggy==0.13.1 py==1.8.1 pyparsing==2.4.6 pytest==5.3.2 six==1.13.0 wcwidth==0.1.8 zipp==0.6.0 nox > pytest ================================= test session starts ================================= platform linux -- Python 3.7.5, pytest-5.3.2, py-1.8.1, pluggy-0.13.1 rootdir: /home/lhn/src/pytest_path_error collected 1 item test_path_error.py F [100%] ====================================== FAILURES ======================================= ________________________________ test_show_wrong_path _________________________________ private_dir = 'ddd' def test_show_wrong_path(private_dir): > assert False E assert False ../test_path_error.py:29: AssertionError ================================== 1 failed in 0.03s ================================== nox > Command pytest failed with exit code 1 nox > Session test failed. Compilation exited abnormally with code 1 at Fri Jan 10 00:06:01 ``` noxfile.py: ```python import nox @nox.session(python='3.7') def test(session): session.install('pytest>=5.3') session.run('pip', 'freeze') session.run('pytest') ```
2020-05-16T14:57:17Z
5.4
["testing/test_nodes.py::test_failure_with_changed_cwd"]
["testing/test_nodes.py::test_ischildnode[--True]", "testing/test_nodes.py::test_ischildnode[-foo-True]", "testing/test_nodes.py::test_ischildnode[-foo/bar-True]", "testing/test_nodes.py::test_ischildnode[-foo/bar::TestBaz-True]", "testing/test_nodes.py::test_ischildnode[foo-food-False]", "testing/test_nodes.py::test_ischildnode[foo/bar::TestBaz-foo/bar-False]", "testing/test_nodes.py::test_ischildnode[foo/bar::TestBaz-foo/bar::TestBop-False]", "testing/test_nodes.py::test_ischildnode[foo/bar-foo/bar::TestBop-True]", "testing/test_nodes.py::test_node_from_parent_disallowed_arguments", "testing/test_nodes.py::test__check_initialpaths_for_relpath", "testing/test_nodes.py::test_std_warn_not_pytestwarning"]
678c1a0745f1cf175c442c719906a1f13e496910
pytest-dev/pytest
pytest-dev__pytest-8365
4964b468c83c06971eb743fbc57cc404f760c573
diff --git a/src/_pytest/tmpdir.py b/src/_pytest/tmpdir.py --- a/src/_pytest/tmpdir.py +++ b/src/_pytest/tmpdir.py @@ -115,7 +115,12 @@ def getbasetemp(self) -> Path: # use a sub-directory in the temproot to speed-up # make_numbered_dir() call rootdir = temproot.joinpath(f"pytest-of-{user}") - rootdir.mkdir(exist_ok=True) + try: + rootdir.mkdir(exist_ok=True) + except OSError: + # getuser() likely returned illegal characters for the platform, use unknown back off mechanism + rootdir = temproot.joinpath("pytest-of-unknown") + rootdir.mkdir(exist_ok=True) basetemp = make_numbered_dir_with_cleanup( prefix="pytest-", root=rootdir, keep=3, lock_timeout=LOCK_TIMEOUT )
diff --git a/testing/test_tmpdir.py b/testing/test_tmpdir.py --- a/testing/test_tmpdir.py +++ b/testing/test_tmpdir.py @@ -11,6 +11,7 @@ import pytest from _pytest import pathlib from _pytest.config import Config +from _pytest.monkeypatch import MonkeyPatch from _pytest.pathlib import cleanup_numbered_dir from _pytest.pathlib import create_cleanup_lock from _pytest.pathlib import make_numbered_dir @@ -445,3 +446,14 @@ def test(tmp_path): # running a second time and ensure we don't crash result = pytester.runpytest("--basetemp=tmp") assert result.ret == 0 + + +def test_tmp_path_factory_handles_invalid_dir_characters( + tmp_path_factory: TempPathFactory, monkeypatch: MonkeyPatch +) -> None: + monkeypatch.setattr("getpass.getuser", lambda: "os/<:*?;>agnostic") + # _basetemp / _given_basetemp are cached / set in parallel runs, patch them + monkeypatch.setattr(tmp_path_factory, "_basetemp", None) + monkeypatch.setattr(tmp_path_factory, "_given_basetemp", None) + p = tmp_path_factory.getbasetemp() + assert "pytest-of-unknown" in str(p)
tmpdir creation fails when the username contains illegal characters for directory names `tmpdir`, `tmpdir_factory` and `tmp_path_factory` rely on `getpass.getuser()` for determining the `basetemp` directory. I found that the user name returned by `getpass.getuser()` may return characters that are not allowed for directory names. This may lead to errors while creating the temporary directory. The situation in which I reproduced this issue was while being logged in through an ssh connection into my Windows 10 x64 Enterprise version (1909) using an OpenSSH_for_Windows_7.7p1 server. In this configuration the command `python -c "import getpass; print(getpass.getuser())"` returns my domain username e.g. `contoso\john_doe` instead of `john_doe` as when logged in regularly using a local session. When trying to create a temp directory in pytest through e.g. `tmpdir_factory.mktemp('foobar')` this fails with the following error message: ``` self = WindowsPath('C:/Users/john_doe/AppData/Local/Temp/pytest-of-contoso/john_doe') mode = 511, parents = False, exist_ok = True def mkdir(self, mode=0o777, parents=False, exist_ok=False): """ Create a new directory at this given path. """ if self._closed: self._raise_closed() try: > self._accessor.mkdir(self, mode) E FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\john_doe\\AppData\\Local\\Temp\\pytest-of-contoso\\john_doe' C:\Python38\lib\pathlib.py:1266: FileNotFoundError ``` I could also reproduce this without the complicated ssh/windows setup with pytest 6.2.2 using the following commands from a `cmd`: ```bat echo def test_tmpdir(tmpdir):>test_tmp.py echo pass>>test_tmp.py set LOGNAME=contoso\john_doe py.test test_tmp.py ``` Thanks for having a look at this!
Thanks for the report @pborsutzki!
2021-02-22T20:26:35Z
6.3
["testing/test_tmpdir.py::test_tmp_path_factory_handles_invalid_dir_characters"]
["testing/test_tmpdir.py::TestTempdirHandler::test_mktemp", "testing/test_tmpdir.py::TestTempdirHandler::test_tmppath_relative_basetemp_absolute", "testing/test_tmpdir.py::test_get_user_uid_not_found", "testing/test_tmpdir.py::TestNumberedDir::test_make", "testing/test_tmpdir.py::TestNumberedDir::test_cleanup_lock_create", "testing/test_tmpdir.py::TestNumberedDir::test_lock_register_cleanup_removal", "testing/test_tmpdir.py::TestNumberedDir::test_cleanup_keep", "testing/test_tmpdir.py::TestNumberedDir::test_cleanup_locked", "testing/test_tmpdir.py::TestNumberedDir::test_cleanup_ignores_symlink", "testing/test_tmpdir.py::TestNumberedDir::test_removal_accepts_lock", "testing/test_tmpdir.py::TestRmRf::test_rm_rf", "testing/test_tmpdir.py::TestRmRf::test_rm_rf_with_read_only_file", "testing/test_tmpdir.py::TestRmRf::test_rm_rf_with_read_only_directory", "testing/test_tmpdir.py::TestRmRf::test_on_rm_rf_error", "testing/test_tmpdir.py::test_tmpdir_equals_tmp_path", "testing/test_tmpdir.py::test_tmpdir_fixture", "testing/test_tmpdir.py::TestConfigTmpdir::test_getbasetemp_custom_removes_old", "testing/test_tmpdir.py::test_mktemp[mypath-True]", "testing/test_tmpdir.py::test_mktemp[/mypath1-False]", "testing/test_tmpdir.py::test_mktemp[./mypath1-True]", "testing/test_tmpdir.py::test_mktemp[../mypath3-False]", "testing/test_tmpdir.py::test_mktemp[../../mypath4-False]", "testing/test_tmpdir.py::test_mktemp[mypath5/..-False]", "testing/test_tmpdir.py::test_mktemp[mypath6/../mypath6-True]", "testing/test_tmpdir.py::test_mktemp[mypath7/../mypath7/..-False]", "testing/test_tmpdir.py::test_tmpdir_always_is_realpath", "testing/test_tmpdir.py::test_tmp_path_always_is_realpath", "testing/test_tmpdir.py::test_tmpdir_too_long_on_parametrization", "testing/test_tmpdir.py::test_tmpdir_factory", "testing/test_tmpdir.py::test_tmpdir_fallback_tox_env", "testing/test_tmpdir.py::test_tmpdir_fallback_uid_not_found", "testing/test_tmpdir.py::test_basetemp_with_read_only_files"]
634312b14a45db8d60d72016e01294284e3a18d4
pytest-dev/pytest
pytest-dev__pytest-8906
69356d20cfee9a81972dcbf93d8caf9eabe113e8
diff --git a/src/_pytest/python.py b/src/_pytest/python.py --- a/src/_pytest/python.py +++ b/src/_pytest/python.py @@ -608,10 +608,10 @@ def _importtestmodule(self): if e.allow_module_level: raise raise self.CollectError( - "Using pytest.skip outside of a test is not allowed. " - "To decorate a test function, use the @pytest.mark.skip " - "or @pytest.mark.skipif decorators instead, and to skip a " - "module use `pytestmark = pytest.mark.{skip,skipif}." + "Using pytest.skip outside of a test will skip the entire module. " + "If that's your intention, pass `allow_module_level=True`. " + "If you want to skip a specific test or an entire class, " + "use the @pytest.mark.skip or @pytest.mark.skipif decorators." ) from e self.config.pluginmanager.consider_module(mod) return mod
diff --git a/testing/test_skipping.py b/testing/test_skipping.py --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -1341,7 +1341,7 @@ def test_func(): ) result = pytester.runpytest() result.stdout.fnmatch_lines( - ["*Using pytest.skip outside of a test is not allowed*"] + ["*Using pytest.skip outside of a test will skip the entire module*"] )
Improve handling of skip for module level This is potentially about updating docs, updating error messages or introducing a new API. Consider the following scenario: `pos_only.py` is using Python 3,8 syntax: ```python def foo(a, /, b): return a + b ``` It should not be tested under Python 3.6 and 3.7. This is a proper way to skip the test in Python older than 3.8: ```python from pytest import raises, skip import sys if sys.version_info < (3, 8): skip(msg="Requires Python >= 3.8", allow_module_level=True) # import must be after the module level skip: from pos_only import * def test_foo(): assert foo(10, 20) == 30 assert foo(10, b=20) == 30 with raises(TypeError): assert foo(a=10, b=20) ``` My actual test involves parameterize and a 3.8 only class, so skipping the test itself is not sufficient because the 3.8 class was used in the parameterization. A naive user will try to initially skip the module like: ```python if sys.version_info < (3, 8): skip(msg="Requires Python >= 3.8") ``` This issues this error: >Using pytest.skip outside of a test is not allowed. To decorate a test function, use the @pytest.mark.skip or @pytest.mark.skipif decorators instead, and to skip a module use `pytestmark = pytest.mark.{skip,skipif}. The proposed solution `pytestmark = pytest.mark.{skip,skipif}`, does not work in my case: pytest continues to process the file and fail when it hits the 3.8 syntax (when running with an older version of Python). The correct solution, to use skip as a function is actively discouraged by the error message. This area feels a bit unpolished. A few ideas to improve: 1. Explain skip with `allow_module_level` in the error message. this seems in conflict with the spirit of the message. 2. Create an alternative API to skip a module to make things easier: `skip_module("reason")`, which can call `_skip(msg=msg, allow_module_level=True)`.
SyntaxErrors are thrown before execution, so how would the skip call stop the interpreter from parsing the 'incorrect' syntax? unless we hook the interpreter that is. A solution could be to ignore syntax errors based on some parameter if needed we can extend this to have some functionality to evaluate conditions in which syntax errors should be ignored please note what i suggest will not fix other compatibility issues, just syntax errors > SyntaxErrors are thrown before execution, so how would the skip call stop the interpreter from parsing the 'incorrect' syntax? The Python 3.8 code is included by an import. the idea is that the import should not happen if we are skipping the module. ```python if sys.version_info < (3, 8): skip(msg="Requires Python >= 3.8", allow_module_level=True) # import must be after the module level skip: from pos_only import * ``` Hi @omry, Thanks for raising this. Definitely we should improve that message. > Explain skip with allow_module_level in the error message. this seems in conflict with the spirit of the message. I'm 👍 on this. 2 is also good, but because `allow_module_level` already exists and is part of the public API, I don't think introducing a new API will really help, better to improve the docs of what we already have. Perhaps improve the message to something like this: ``` Using pytest.skip outside of a test will skip the entire module, if that's your intention pass `allow_module_level=True`. If you want to skip a specific test or entire class, use the @pytest.mark.skip or @pytest.mark.skipif decorators. ``` I think we can drop the `pytestmark` remark from there, it is not skip-specific and passing `allow_module_level` already accomplishes the same. Thanks @nicoddemus. > Using pytest.skip outside of a test will skip the entire module, if that's your intention pass `allow_module_level=True`. If you want to skip a specific test or entire class, use the @pytest.mark.skip or @pytest.mark.skipif decorators. This sounds clearer. Can you give a bit of context of why the message is there in the first place? It sounds like we should be able to automatically detect if this is skipping a test or skipping the entire module (based on the fact that we can issue the warning). Maybe this is addressing some past confusion, or we want to push people toward `pytest.mark.skip[if]`, but if we can detect it automatically - we can also deprecate allow_module_level and make `skip()` do the right thing based on the context it's used in. > Maybe this is addressing some past confusion That's exactly it, people would use `@pytest.skip` instead of `@pytest.mark.skip` and skip the whole module: https://github.com/pytest-dev/pytest/issues/2338#issuecomment-290324255 For that reason we don't really want to automatically detect things, but want users to explicitly pass that flag which proves they are not doing it by accident. Original issue: https://github.com/pytest-dev/pytest/issues/607 Having looked at the links, I think the alternative API to skip a module is more appealing. Here is a proposed end state: 1. pytest.skip_module is introduced, can be used to skip a module. 2. pytest.skip() is only legal inside of a test. If called outside of a test, an error message is issues. Example: > pytest.skip should only be used inside tests. To skip a module use pytest.skip_module. To completely skip a test function or a test class, use the @pytest.mark.skip or @pytest.mark.skipif decorators. Getting to this end state would include deprecating allow_module_level first, directing people using pytest.skip(allow_module_level=True) to use pytest.skip_module(). I am also fine with just changing the message as you initially proposed but I feel this proposal will result in an healthier state. -0.5 from my side - I think this is too minor to warrant another deprecation and change. I agree it would be healthier, but -1 from me for the same reasons as @The-Compiler: we already had a deprecation/change period in order to introduce `allow_module_level`, having yet another one is frustrating/confusing to users, in comparison to the small gains. Hi, I see that this is still open. If available, I'd like to take this up.
2021-07-14T08:00:50Z
7.0
["testing/test_skipping.py::test_module_level_skip_error"]
["testing/test_skipping.py::test_importorskip", "testing/test_skipping.py::TestEvaluation::test_no_marker", "testing/test_skipping.py::TestEvaluation::test_marked_xfail_no_args", "testing/test_skipping.py::TestEvaluation::test_marked_skipif_no_args", "testing/test_skipping.py::TestEvaluation::test_marked_one_arg", "testing/test_skipping.py::TestEvaluation::test_marked_one_arg_with_reason", "testing/test_skipping.py::TestEvaluation::test_marked_one_arg_twice", "testing/test_skipping.py::TestEvaluation::test_marked_one_arg_twice2", "testing/test_skipping.py::TestEvaluation::test_marked_skipif_with_boolean_without_reason", "testing/test_skipping.py::TestEvaluation::test_marked_skipif_with_invalid_boolean", "testing/test_skipping.py::TestEvaluation::test_skipif_class", "testing/test_skipping.py::TestEvaluation::test_skipif_markeval_namespace", "testing/test_skipping.py::TestEvaluation::test_skipif_markeval_namespace_multiple", "testing/test_skipping.py::TestEvaluation::test_skipif_markeval_namespace_ValueError", "testing/test_skipping.py::TestXFail::test_xfail_simple[True]", "testing/test_skipping.py::TestXFail::test_xfail_simple[False]", "testing/test_skipping.py::TestXFail::test_xfail_xpassed", "testing/test_skipping.py::TestXFail::test_xfail_using_platform", "testing/test_skipping.py::TestXFail::test_xfail_xpassed_strict", "testing/test_skipping.py::TestXFail::test_xfail_run_anyway", "testing/test_skipping.py::TestXFail::test_xfail_run_with_skip_mark[test_input0-expected0]", "testing/test_skipping.py::TestXFail::test_xfail_run_with_skip_mark[test_input1-expected1]", "testing/test_skipping.py::TestXFail::test_xfail_evalfalse_but_fails", "testing/test_skipping.py::TestXFail::test_xfail_not_report_default", "testing/test_skipping.py::TestXFail::test_xfail_not_run_xfail_reporting", "testing/test_skipping.py::TestXFail::test_xfail_not_run_no_setup_run", "testing/test_skipping.py::TestXFail::test_xfail_xpass", "testing/test_skipping.py::TestXFail::test_xfail_imperative", "testing/test_skipping.py::TestXFail::test_xfail_imperative_in_setup_function", "testing/test_skipping.py::TestXFail::test_dynamic_xfail_no_run", "testing/test_skipping.py::TestXFail::test_dynamic_xfail_set_during_funcarg_setup", "testing/test_skipping.py::TestXFail::test_dynamic_xfail_set_during_runtest_failed", "testing/test_skipping.py::TestXFail::test_dynamic_xfail_set_during_runtest_passed_strict", "testing/test_skipping.py::TestXFail::test_xfail_raises[TypeError-TypeError-*1", "testing/test_skipping.py::TestXFail::test_xfail_raises[(AttributeError,", "testing/test_skipping.py::TestXFail::test_xfail_raises[TypeError-IndexError-*1", "testing/test_skipping.py::TestXFail::test_strict_sanity", "testing/test_skipping.py::TestXFail::test_strict_xfail[True]", "testing/test_skipping.py::TestXFail::test_strict_xfail[False]", "testing/test_skipping.py::TestXFail::test_strict_xfail_condition[True]", "testing/test_skipping.py::TestXFail::test_strict_xfail_condition[False]", "testing/test_skipping.py::TestXFail::test_xfail_condition_keyword[True]", "testing/test_skipping.py::TestXFail::test_xfail_condition_keyword[False]", "testing/test_skipping.py::TestXFail::test_strict_xfail_default_from_file[true]", "testing/test_skipping.py::TestXFail::test_strict_xfail_default_from_file[false]", "testing/test_skipping.py::TestXFail::test_xfail_markeval_namespace", "testing/test_skipping.py::TestXFailwithSetupTeardown::test_failing_setup_issue9", "testing/test_skipping.py::TestXFailwithSetupTeardown::test_failing_teardown_issue9", "testing/test_skipping.py::TestSkip::test_skip_class", "testing/test_skipping.py::TestSkip::test_skips_on_false_string", "testing/test_skipping.py::TestSkip::test_arg_as_reason", "testing/test_skipping.py::TestSkip::test_skip_no_reason", "testing/test_skipping.py::TestSkip::test_skip_with_reason", "testing/test_skipping.py::TestSkip::test_only_skips_marked_test", "testing/test_skipping.py::TestSkip::test_strict_and_skip", "testing/test_skipping.py::TestSkip::test_wrong_skip_usage", "testing/test_skipping.py::TestSkipif::test_skipif_conditional", "testing/test_skipping.py::TestSkipif::test_skipif_reporting[\"hasattr(sys,", "testing/test_skipping.py::TestSkipif::test_skipif_reporting[True,", "testing/test_skipping.py::TestSkipif::test_skipif_using_platform", "testing/test_skipping.py::TestSkipif::test_skipif_reporting_multiple[skipif-SKIP-skipped]", "testing/test_skipping.py::TestSkipif::test_skipif_reporting_multiple[xfail-XPASS-xpassed]", "testing/test_skipping.py::test_skip_not_report_default", "testing/test_skipping.py::test_skipif_class", "testing/test_skipping.py::test_skipped_reasons_functional", "testing/test_skipping.py::test_skipped_folding", "testing/test_skipping.py::test_reportchars", "testing/test_skipping.py::test_reportchars_error", "testing/test_skipping.py::test_reportchars_all", "testing/test_skipping.py::test_reportchars_all_error", "testing/test_skipping.py::test_errors_in_xfail_skip_expressions", "testing/test_skipping.py::test_xfail_skipif_with_globals", "testing/test_skipping.py::test_default_markers", "testing/test_skipping.py::test_xfail_test_setup_exception", "testing/test_skipping.py::test_imperativeskip_on_xfail_test", "testing/test_skipping.py::TestBooleanCondition::test_skipif", "testing/test_skipping.py::TestBooleanCondition::test_skipif_noreason", "testing/test_skipping.py::TestBooleanCondition::test_xfail", "testing/test_skipping.py::test_xfail_item", "testing/test_skipping.py::test_module_level_skip_with_allow_module_level", "testing/test_skipping.py::test_invalid_skip_keyword_parameter", "testing/test_skipping.py::test_mark_xfail_item", "testing/test_skipping.py::test_summary_list_after_errors", "testing/test_skipping.py::test_relpath_rootdir"]
e2ee3144ed6e241dea8d96215fcdca18b3892551
pylint-dev/pylint
pylint-dev__pylint-7228
d597f252915ddcaaa15ccdfcb35670152cb83587
diff --git a/pylint/config/argument.py b/pylint/config/argument.py --- a/pylint/config/argument.py +++ b/pylint/config/argument.py @@ -99,11 +99,20 @@ def _py_version_transformer(value: str) -> tuple[int, ...]: return version +def _regex_transformer(value: str) -> Pattern[str]: + """Return `re.compile(value)`.""" + try: + return re.compile(value) + except re.error as e: + msg = f"Error in provided regular expression: {value} beginning at index {e.pos}: {e.msg}" + raise argparse.ArgumentTypeError(msg) + + def _regexp_csv_transfomer(value: str) -> Sequence[Pattern[str]]: """Transforms a comma separated list of regular expressions.""" patterns: list[Pattern[str]] = [] for pattern in _csv_transformer(value): - patterns.append(re.compile(pattern)) + patterns.append(_regex_transformer(pattern)) return patterns @@ -130,7 +139,7 @@ def _regexp_paths_csv_transfomer(value: str) -> Sequence[Pattern[str]]: "non_empty_string": _non_empty_string_transformer, "path": _path_transformer, "py_version": _py_version_transformer, - "regexp": re.compile, + "regexp": _regex_transformer, "regexp_csv": _regexp_csv_transfomer, "regexp_paths_csv": _regexp_paths_csv_transfomer, "string": pylint_utils._unquote,
diff --git a/tests/config/test_config.py b/tests/config/test_config.py --- a/tests/config/test_config.py +++ b/tests/config/test_config.py @@ -111,6 +111,36 @@ def test_unknown_py_version(capsys: CaptureFixture) -> None: assert "the-newest has an invalid format, should be a version string." in output.err +def test_regex_error(capsys: CaptureFixture) -> None: + """Check that we correctly error when an an option is passed whose value is an invalid regular expression.""" + with pytest.raises(SystemExit): + Run( + [str(EMPTY_MODULE), r"--function-rgx=[\p{Han}a-z_][\p{Han}a-z0-9_]{2,30}$"], + exit=False, + ) + output = capsys.readouterr() + assert ( + r"Error in provided regular expression: [\p{Han}a-z_][\p{Han}a-z0-9_]{2,30}$ beginning at index 1: bad escape \p" + in output.err + ) + + +def test_csv_regex_error(capsys: CaptureFixture) -> None: + """Check that we correctly error when an option is passed and one + of its comma-separated regular expressions values is an invalid regular expression. + """ + with pytest.raises(SystemExit): + Run( + [str(EMPTY_MODULE), r"--bad-names-rgx=(foo{1,3})"], + exit=False, + ) + output = capsys.readouterr() + assert ( + r"Error in provided regular expression: (foo{1 beginning at index 0: missing ), unterminated subpattern" + in output.err + ) + + def test_short_verbose(capsys: CaptureFixture) -> None: """Check that we correctly handle the -v flag.""" Run([str(EMPTY_MODULE), "-v"], exit=False)
# Enhanced Problem Statement: Pylint Regular Expression Unicode Property Support Issue ## Issue Description Pylint fails to process configuration files that include regular expressions with Unicode property patterns like `\p{Han}`. When such patterns are used in the `.pylintrc` file (e.g., for defining naming conventions that support Chinese characters), Pylint crashes during initialization with a "bad escape \p" error. This occurs because Pylint uses Python's standard `re` module which doesn't support Unicode property syntax (`\p{X}`), unlike other regex engines such as PCRE. The error happens during the configuration parsing phase, specifically when the argument parser attempts to validate and compile the regular expression patterns from the config file. ## Reproduction Steps 1. Create a `.pylintrc` file with a regex pattern using Unicode property syntax: ```ini function-rgx=[\p{Han}a-z_][\p{Han}a-z0-9_]{2,30}$ ``` 2. Run pylint in a directory containing this config file: ```shell pylint ``` 3. The error occurs during Pylint's initialization when it attempts to process the configuration: - The `_parse_configuration_file` method reads the config file - The regex pattern is passed to Python's argparse for processing - Argparse attempts to validate the regex by calling `re.compile(pattern)` - Python's `re` module fails to parse the Unicode property pattern `\p{Han}` - An error is raised: `re.error: bad escape \p at position 1` ## Expected Behavior Pylint should successfully process configuration files with Unicode property patterns like `\p{Han}`. This would allow users to define naming conventions that support Chinese characters and other non-Latin scripts. Either Pylint should: 1. Handle such patterns by preprocessing them into compatible regex syntax 2. Use an alternative regex library that supports Unicode properties 3. Provide a clear error message explaining that this syntax is not supported, with suggestions for alternatives ## Exploration Hints ### Files to Examine: - `pylint/config/config_initialization.py` - Contains the `_config_initialization` function where the error occurs during configuration processing - `pylint/config/arguments_manager.py` - Contains the `_parse_configuration_file` method that handles configuration file processing - `pylint/checkers/base/name_checker/naming_style.py` - Defines how regular expressions are used for naming style validation - `pylint/checkers/base/name_checker/checker.py` - Contains the NameChecker class which uses the regex patterns ### Key Classes/Functions: - `_parse_configuration_file()` - This method is where the configuration file is processed and where the error occurs when regex validation happens - `NameChecker` class - Handles naming convention checking using the regex patterns from configuration - The argument type validation logic - Responsible for validating configuration values, including regex patterns ### Areas of Interest: - How regex type options are defined and processed in the configuration system - The integration between the configuration system and Python's regex engine - The validation process for configuration values, particularly regex patterns ## Fix Hints ### High Confidence Locations: - The configuration handling code in `pylint/config/arguments_manager.py` - This is where the regex patterns from config are processed before reaching the regex compiler ### Implementation Hints: 1. **Use a Different Regex Library**: Replace Python's standard `re` module with the third-party `regex` library which supports Unicode property syntax like `\p{Han}`. 2. **Preprocess Regex Patterns**: Intercept regex patterns from configuration before validation and convert Unicode property syntax to equivalent character ranges: - Convert `\p{Han}` to an explicit range of Chinese characters - This would require maintaining mappings of Unicode properties to character ranges 3. **Custom Regex Type Handler**: Create a custom validation function for regex patterns that catches and gracefully handles Unicode property syntax 4. **Documentation Update**: If supporting Unicode properties is not feasible, update documentation to clearly state this limitation and suggest alternatives ### Alternative Hypotheses: 1. The issue might be related to how regex patterns are escaped or unescaped when reading from configuration files, potentially causing malformed patterns 2. There could be encoding-related issues when reading configuration files with non-ASCII content that compound the regex processing problem 3. The error might be occurring in a different location than expected, such as in the configuration system's type validation logic rather than in the name checker itself 4. There might already be an alternative mechanism in Pylint for supporting Unicode character ranges that is not well-documented
This doesn't seem like it is a `pylint` issue? `re.compile("[\p{Han}a-z_]")` also raises normally. `\p` also isn't documented: https://docs.python.org/3/howto/regex.html Is this a supported character? I think this could be improved! Similar to the helpful output when passing an unrecognized option to Pylint, we could give a friendly output indicating that the regex pattern is invalid without the traceback; happy to put a MR together if you agree. Thanks @mbyrnepr2 I did not even realize it was a crash that we had to fix before your comment. @mbyrnepr2 I think in the above stacktrace on line 1858 makes the most sense. We need to decide though if we continue to run the program. I think it makes sense to still quit. If we catch regex errors there and pass we will also "allow" ignore path regexes that don't work. I don't think we should do that. Imo, incorrect regexes are a little different from other "incorrect" options, since there is little risk that they are valid on other interpreters or versions such as old messages etc. Therefore, I'd prefer to (cleanly) exit. Indeed @DanielNoord I think we are on the same page regarding this point; I would also exit instead of passing if the regex is invalid. That line you mention, we can basically try/except on re.error and exit printing the details of the pattern which is invalid.
2022-07-25T17:19:11Z
2.15
["tests/config/test_config.py::test_regex_error", "tests/config/test_config.py::test_csv_regex_error"]
["tests/config/test_config.py::test_can_read_toml_env_variable", "tests/config/test_config.py::test_unknown_message_id", "tests/config/test_config.py::test_unknown_option_name", "tests/config/test_config.py::test_unknown_short_option_name", "tests/config/test_config.py::test_unknown_confidence", "tests/config/test_config.py::test_empty_confidence", "tests/config/test_config.py::test_unknown_yes_no", "tests/config/test_config.py::test_unknown_py_version", "tests/config/test_config.py::test_short_verbose", "tests/config/test_config.py::test_argument_separator"]
e90702074e68e20dc8e5df5013ee3ecf22139c3e
pydata/xarray
pydata__xarray-4248
98dc1f4ea18738492e074e9e51ddfed5cd30ab94
diff --git a/xarray/core/formatting.py b/xarray/core/formatting.py --- a/xarray/core/formatting.py +++ b/xarray/core/formatting.py @@ -261,6 +261,8 @@ def inline_variable_array_repr(var, max_width): return inline_dask_repr(var.data) elif isinstance(var._data, sparse_array_type): return inline_sparse_repr(var.data) + elif hasattr(var._data, "_repr_inline_"): + return var._data._repr_inline_(max_width) elif hasattr(var._data, "__array_function__"): return maybe_truncate(repr(var._data).replace("\n", " "), max_width) else:
diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py --- a/xarray/tests/test_formatting.py +++ b/xarray/tests/test_formatting.py @@ -7,6 +7,7 @@ import xarray as xr from xarray.core import formatting +from xarray.core.npcompat import IS_NEP18_ACTIVE from . import raises_regex @@ -391,6 +392,44 @@ def test_array_repr(self): assert actual == expected +@pytest.mark.skipif(not IS_NEP18_ACTIVE, reason="requires __array_function__") +def test_inline_variable_array_repr_custom_repr(): + class CustomArray: + def __init__(self, value, attr): + self.value = value + self.attr = attr + + def _repr_inline_(self, width): + formatted = f"({self.attr}) {self.value}" + if len(formatted) > width: + formatted = f"({self.attr}) ..." + + return formatted + + def __array_function__(self, *args, **kwargs): + return NotImplemented + + @property + def shape(self): + return self.value.shape + + @property + def dtype(self): + return self.value.dtype + + @property + def ndim(self): + return self.value.ndim + + value = CustomArray(np.array([20, 40]), "m") + variable = xr.Variable("x", value) + + max_width = 10 + actual = formatting.inline_variable_array_repr(variable, max_width=10) + + assert actual == value._repr_inline_(max_width) + + def test_set_numpy_options(): original_options = np.get_printoptions() with formatting.set_numpy_options(threshold=10):
# Enhanced Problem Statement: Display Units in xarray Dataset Overview ## Issue Description xarray's Dataset overview currently doesn't show units for coordinates and data variables in its string representation. Users would benefit from seeing unit information directly in the overview display without needing to inspect variable attributes separately. The feature request is to enhance the string representation of Dataset objects to include units, which are typically stored in the variables' `attrs` dictionary under the key 'units'. This involves modifying the formatting system in xarray that builds the string representations for both plain text and HTML outputs. ## Reproduction Steps No error is being reported - this is a feature request. The current representation of a Dataset looks like: ```python # Current representation <xarray.Dataset> Dimensions: (time: 3, x: 988, y: 822) Coordinates: * x (x) float64 ... * y (y) float64 ... * time (time) datetime64[ns] ... Data variables: rainfall (time, y, x) float32 ... max_temp (time, y, x) float32 ... ``` The requested representation would show units for both coordinates and data variables: ```python # Desired representation <xarray.Dataset> Dimensions: (time: 3, x: 988, y: 822) Coordinates: * x, in metres (x) float64 ... * y, in metres (y) float64 ... * time (time) datetime64[ns] ... Data variables: rainfall, in mm (time, y, x) float32 ... max_temp, in deg C (time, y, x) float32 ... ``` To recreate a testable example, you could create a Dataset with units: ```python import xarray as xr import numpy as np # Create example dataset with units ds = xr.Dataset( data_vars={ "rainfall": (["time", "y", "x"], np.random.rand(3, 5, 4), {"units": "mm"}), "max_temp": (["time", "y", "x"], np.random.rand(3, 5, 4), {"units": "deg C"}), }, coords={ "x": ("x", np.arange(4), {"units": "metres"}), "y": ("y", np.arange(5), {"units": "metres"}), "time": pd.date_range("2000-01-01", periods=3), }, ) # Current representation doesn't show units print(ds) ``` ## Expected Behavior The string representation of the Dataset should include unit information for both coordinates and data variables, following the format: `variable_name, in unit_value`. The units should be extracted from the 'units' attribute of each variable. If a variable doesn't have a units attribute, it should be displayed without unit information. The formatting should maintain alignment and readability while accommodating the additional unit information. ## Exploration Hints ### Files to Examine: - **xarray/core/formatting.py** - This is the primary file responsible for generating the text representation of Dataset objects. It contains the functions for formatting coordinates and data variables, and would need to be modified to include unit information from variable attributes. - **xarray/core/formatting_html.py** - Contains HTML representation code for Jupyter notebook display. Would need similar changes for consistency between text and HTML representations. - **xarray/tests/test_formatting.py** - Contains tests for the formatting functionality. New tests would need to be added to verify the unit display works correctly. ### Key Classes/Functions: - **summarize_coord()** in formatting.py - Creates string representations for coordinates. Would need to be modified to extract and include unit information. - **summarize_datavar()** in formatting.py - Similar function for data variables. Would need to include unit information. - **Dataset.__repr__()** - Generates the string representation that users see when printing a Dataset. Calls the formatting functions. - **_calculate_col_width()** - Would need updates to account for additional text from unit information. ### Areas of Interest: - The formatting system builds string representations by collecting information from coordinates and variables, then formatting them into aligned columns. - Unit information is stored in variable attributes, typically under the key 'units', following CF conventions. - The current display uses a column-based layout with careful attention to width constraints and alignment, which must be preserved. - Both plain text and HTML representations should be updated for consistency. ## Fix Hints ### High Confidence Locations: - The `summarize_coord()` and `summarize_datavar()` functions in formatting.py are the most likely places to modify. These functions build the string representation for each variable and would need to extract unit information from variable attributes. - The equivalent functions in formatting_html.py would need similar changes for HTML representation. ### Implementation Hints: - For each variable, check for the presence of a 'units' attribute: `var.attrs.get('units')` - If present, append the unit information to the variable name: `f"{name}, in {units}"` - Adjust column width calculations to account for the additional text - Consider handling special cases like time variables which might use different unit conventions - Ensure backward compatibility for datasets without unit information ### Alternative Hypotheses: - Units might need to be obtained from more complex sources than just the 'units' attribute. There could be unit registry integrations or other frameworks involved. - The feature might be better implemented as a configuration option rather than changing the default behavior, allowing users to toggle unit display. - The representation might need a more comprehensive redesign to handle units as first-class citizens rather than just attributes, especially if xarray plans to enhance its units support more broadly. - The implementation might need to consider other metadata beyond just units, as this could open the door to displaying other important attributes in the overview.
I would love to see this. What would we want the exact formatting to be? Square brackets to copy how units from `attrs['units']` are displayed on plots? e.g. ``` <xarray.Dataset> Dimensions: (time: 3, x: 988, y: 822) Coordinates: * x [m] (x) float64 ... * y [m] (y) float64 ... * time [s] (time) datetime64[ns] ... Data variables: rainfall [mm] (time, y, x) float32 ... max_temp [deg C] (time, y, x) float32 ... ``` The lack of vertical alignment is kind of ugly... There are now two cases to discuss: units in `attrs`, and unit-aware arrays like pint. (If we do the latter we may not need the former though...) from @keewis on #3616: >At the moment, the formatting.diff_*_repr functions that provide the pretty-printing for assert_* use repr to format NEP-18 strings, truncating the result if it is too long. In the case of pint's quantities, this makes the pretty printing useless since only a few values are visible and the unit is in the truncated part. > > What should we about this? Does pint have to change its repr? We could presumably just extract the units from pint's repr to display them separately. I don't know if that raises questions about generality of duck-typing arrays though @dcherian ? Is it fine to make units a special-case? it was argued in pint that the unit is part of the data, so we should keep it as close to the data as possible. How about ``` <xarray.Dataset> Dimensions: (time: 3, x: 988, y: 822) Coordinates: * x (x) [m] float64 ... * y (y) [m] float64 ... * time (time) [s] datetime64[ns] ... Data variables: rainfall (time, y, x) [mm] float32 ... max_temp (time, y, x) [deg C] float32 ... ``` or ``` <xarray.Dataset> Dimensions: (time: 3, x: 988, y: 822) Coordinates: * x (x) float64 [m] ... * y (y) float64 [m] ... * time (time) datetime64[ns] [s] ... Data variables: rainfall (time, y, x) float32 [mm] ... max_temp (time, y, x) float32 [deg C] ... ``` The issue with the second example is that it is easy to confuse with numpy's dtype, though. Maybe we should use parentheses instead? re special casing: I think would be fine for attributes since we already special case them for plotting, but I don't know about duck arrays. Even if we want to special case them, there are many unit libraries with different interfaces so we would either need to special case all of them or require a specific interface (or a function to retrieve the necessary data?). Also, we should keep in mind is that using more horizontal space for the units results in less space for data. And we should not forget about https://github.com/dask/dask/issues/5329#issue-485927396, where a different kind of format was proposed, at least for the values of a `DataArray`. Instead of trying to come up with our own formatting, how about supporting a `_repr_short_(self, length)` method on the duck array (with a fall back to the current behavior)? That way duck arrays have to explicitly define the format (or have a compatibility package like `pint-xarray` provide it for them) if they want something different from their normal repr and we don't have to add duck array specific code. This won't help with displaying the `units` attributes (which we don't really need once we have support for pint arrays in indexes).
2020-07-22T14:54:03Z
0.12
["xarray/tests/test_formatting.py::test_inline_variable_array_repr_custom_repr"]
["xarray/tests/test_formatting.py::TestFormatting::test_get_indexer_at_least_n_items", "xarray/tests/test_formatting.py::TestFormatting::test_first_n_items", "xarray/tests/test_formatting.py::TestFormatting::test_last_n_items", "xarray/tests/test_formatting.py::TestFormatting::test_last_item", "xarray/tests/test_formatting.py::TestFormatting::test_format_item", "xarray/tests/test_formatting.py::TestFormatting::test_format_items", "xarray/tests/test_formatting.py::TestFormatting::test_format_array_flat", "xarray/tests/test_formatting.py::TestFormatting::test_pretty_print", "xarray/tests/test_formatting.py::TestFormatting::test_maybe_truncate", "xarray/tests/test_formatting.py::TestFormatting::test_format_timestamp_out_of_bounds", "xarray/tests/test_formatting.py::TestFormatting::test_attribute_repr", "xarray/tests/test_formatting.py::TestFormatting::test_diff_array_repr", "xarray/tests/test_formatting.py::TestFormatting::test_diff_attrs_repr_with_array", "xarray/tests/test_formatting.py::TestFormatting::test_diff_dataset_repr", "xarray/tests/test_formatting.py::TestFormatting::test_array_repr", "xarray/tests/test_formatting.py::test_set_numpy_options", "xarray/tests/test_formatting.py::test_short_numpy_repr", "xarray/tests/test_formatting.py::test_large_array_repr_length"]
1c198a191127c601d091213c4b3292a8bb3054e1
sphinx-doc/sphinx
sphinx-doc__sphinx-8506
e4bd3bd3ddd42c6642ff779a4f7381f219655c2c
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py --- a/sphinx/domains/std.py +++ b/sphinx/domains/std.py @@ -43,7 +43,7 @@ # RE for option descriptions -option_desc_re = re.compile(r'((?:/|--|-|\+)?[^\s=[]+)(=?\s*.*)') +option_desc_re = re.compile(r'((?:/|--|-|\+)?[^\s=]+)(=?\s*.*)') # RE for grammar tokens token_re = re.compile(r'`(\w+)`', re.U) @@ -197,6 +197,11 @@ def handle_signature(self, sig: str, signode: desc_signature) -> str: location=signode) continue optname, args = m.groups() + if optname.endswith('[') and args.endswith(']'): + # optional value surrounded by brackets (ex. foo[=bar]) + optname = optname[:-1] + args = '[' + args + if count: signode += addnodes.desc_addname(', ', ', ') signode += addnodes.desc_name(optname, optname)
diff --git a/tests/test_domain_std.py b/tests/test_domain_std.py --- a/tests/test_domain_std.py +++ b/tests/test_domain_std.py @@ -91,6 +91,28 @@ def test_get_full_qualified_name(): assert domain.get_full_qualified_name(node) == 'ls.-l' +def test_cmd_option_with_optional_value(app): + text = ".. option:: -j[=N]" + doctree = restructuredtext.parse(app, text) + assert_node(doctree, (index, + [desc, ([desc_signature, ([desc_name, '-j'], + [desc_addname, '[=N]'])], + [desc_content, ()])])) + objects = list(app.env.get_domain("std").get_objects()) + assert ('-j', '-j', 'cmdoption', 'index', 'cmdoption-j', 1) in objects + + +def test_cmd_option_starting_with_bracket(app): + text = ".. option:: [enable=]PATTERN" + doctree = restructuredtext.parse(app, text) + assert_node(doctree, (index, + [desc, ([desc_signature, ([desc_name, '[enable'], + [desc_addname, '=]PATTERN'])], + [desc_content, ()])])) + objects = list(app.env.get_domain("std").get_objects()) + assert ('[enable', '[enable', 'cmdoption', 'index', 'cmdoption-arg-enable', 1) in objects + + def test_glossary(app): text = (".. glossary::\n" "\n"
Sphinx 3.2 complains about option:: syntax that earlier versions accepted Sphinx 3.2 complains about use of the option:: directive that earlier versions accepted without complaint. The QEMU documentation includes this: ``` .. option:: [enable=]PATTERN Immediately enable events matching *PATTERN* ``` as part of the documentation of the command line options of one of its programs. Earlier versions of Sphinx were fine with this, but Sphinx 3.2 complains: ``` Warning, treated as error: ../../docs/qemu-option-trace.rst.inc:4:Malformed option description '[enable=]PATTERN', should look like "opt", "-opt args", "--opt args", "/opt args" or "+opt args" ``` Sphinx ideally shouldn't change in ways that break the building of documentation that worked in older versions, because this makes it unworkably difficult to have documentation that builds with whatever the Linux distro's sphinx-build is. The error message suggests that Sphinx has a very restrictive idea of what option syntax is; it would be better if it just accepted any string, because not all programs and OSes have option syntax that matches the limited list the error message indicates.
I disagree with > Sphinx ideally shouldn't change in ways that break the building of documentation that worked in older versions, because this makes it unworkably difficult to have documentation that builds with whatever the Linux distro's sphinx-build is. The idea that things shouldn't change to avoid breaking is incredibly toxic developer culture. This is what pinned versions are for, additionally, you can have your project specify a minimum and maximum sphinx as a requirement. I agree that there's some philosophical differences at play here. Our project wants to be able to build on a fairly wide range of supported and shipping distributions (we go for "the versions of major distros still supported by the distro vendor", roughly), and we follow the usual/traditional C project/Linux distro approach of "build with the versions of libraries, dependencies and tools shipped by the build platform" generally. At the moment that means we need our docs to build with Sphinx versions ranging from 1.6 through to 3.2, and the concept of a "pinned version" just doesn't exist in this ecosystem. Being able to build with the distro version of Sphinx is made much more awkward if the documentation markup language is not a well specified and stable target for documentation authors to aim at. Incidentally, the current documentation of the option:: directive in https://www.sphinx-doc.org/en/master/usage/restructuredtext/domains.html?highlight=option#directive-option says nothing about this requirement for -, --, / or +. For the moment I've dealt with this by rewriting the fragment of documentation to avoid the option directive. I don't want to get into an argument if the Sphinx project doesn't feel that strong backward-compatibility guarantees are a project goal, so I thought I'd just write up my suggestions/hopes for sphinx-build more generally for you to consider (or reject!) and leave it at that: * Where directives/markup have a required syntax for their arguments, it would be useful if the documentation clearly and precisely described the syntax. That allows documentation authors to know whether they're using something as intended. * Where possible, the initial implementation should start with tightly parsing that syntax and diagnosing errors. It's much easier to loosen restrictions or use a previously forbidden syntax for a new purpose if older implementations just rejected it rather than if they accepted it and did something different because they didn't parse it very strictly. * Where major changes are necessary, a reasonable length period of deprecation and parallel availability of old and new syntax helps to ease transitions. and on a more general note I would appreciate it if the project considered the needs of external non-Python projects that have adopted Sphinx as a documentation system but which don't necessarily have the same control over tooling versions that Python-ecosystem projects might. (The Linux kernel is another good example here.) > Where major changes are necessary, a reasonable length period of deprecation and parallel availability of old and new syntax helps to ease transitions. Major versions are done via semver, where Sphinx 2 is a major breaking change over Sphinx 1, and Sphinx 3 breaks changes over Sphinx 2. What other things could be done? The concept of deprecation isn't as common in Python communities due to the popularity of fixed versions or locking to a major version. IE ``pip install sphinx==3`` which installs the latest major sphinx version of 3. This change was added at https://github.com/sphinx-doc/sphinx/pull/7770. It is not an expected change. It means this is a mere bug.
2020-11-28T17:28:05Z
3.4
["tests/test_domain_std.py::test_cmd_option_starting_with_bracket"]
["tests/test_domain_std.py::test_process_doc_handle_figure_caption", "tests/test_domain_std.py::test_process_doc_handle_table_title", "tests/test_domain_std.py::test_get_full_qualified_name", "tests/test_domain_std.py::test_cmd_option_with_optional_value", "tests/test_domain_std.py::test_glossary", "tests/test_domain_std.py::test_glossary_warning", "tests/test_domain_std.py::test_glossary_comment", "tests/test_domain_std.py::test_glossary_comment2", "tests/test_domain_std.py::test_glossary_sorted", "tests/test_domain_std.py::test_glossary_alphanumeric", "tests/test_domain_std.py::test_glossary_conflicted_labels", "tests/test_domain_std.py::test_cmdoption", "tests/test_domain_std.py::test_multiple_cmdoptions", "tests/test_domain_std.py::test_disabled_docref"]
3f560cd67239f75840cc7a439ab54d8509c855f6
sphinx-doc/sphinx
sphinx-doc__sphinx-8474
3ea1ec84cc610f7a9f4f6b354e264565254923ff
diff --git a/sphinx/domains/std.py b/sphinx/domains/std.py --- a/sphinx/domains/std.py +++ b/sphinx/domains/std.py @@ -852,8 +852,9 @@ def _resolve_numref_xref(self, env: "BuildEnvironment", fromdocname: str, if fignumber is None: return contnode except ValueError: - logger.warning(__("no number is assigned for %s: %s"), figtype, labelid, - location=node) + logger.warning(__("Failed to create a cross reference. Any number is not " + "assigned: %s"), + labelid, location=node) return contnode try:
diff --git a/tests/test_build_html.py b/tests/test_build_html.py --- a/tests/test_build_html.py +++ b/tests/test_build_html.py @@ -660,7 +660,7 @@ def test_numfig_without_numbered_toctree_warn(app, warning): warnings = warning.getvalue() assert 'index.rst:47: WARNING: numfig is disabled. :numref: is ignored.' not in warnings - assert 'index.rst:55: WARNING: no number is assigned for section: index' in warnings + assert 'index.rst:55: WARNING: Failed to create a cross reference. Any number is not assigned: index' in warnings assert 'index.rst:56: WARNING: invalid numfig_format: invalid' in warnings assert 'index.rst:57: WARNING: invalid numfig_format: Fig %s %s' in warnings @@ -768,7 +768,7 @@ def test_numfig_with_numbered_toctree_warn(app, warning): app.build() warnings = warning.getvalue() assert 'index.rst:47: WARNING: numfig is disabled. :numref: is ignored.' not in warnings - assert 'index.rst:55: WARNING: no number is assigned for section: index' in warnings + assert 'index.rst:55: WARNING: Failed to create a cross reference. Any number is not assigned: index' in warnings assert 'index.rst:56: WARNING: invalid numfig_format: invalid' in warnings assert 'index.rst:57: WARNING: invalid numfig_format: Fig %s %s' in warnings @@ -873,7 +873,7 @@ def test_numfig_with_prefix_warn(app, warning): app.build() warnings = warning.getvalue() assert 'index.rst:47: WARNING: numfig is disabled. :numref: is ignored.' not in warnings - assert 'index.rst:55: WARNING: no number is assigned for section: index' in warnings + assert 'index.rst:55: WARNING: Failed to create a cross reference. Any number is not assigned: index' in warnings assert 'index.rst:56: WARNING: invalid numfig_format: invalid' in warnings assert 'index.rst:57: WARNING: invalid numfig_format: Fig %s %s' in warnings @@ -979,7 +979,7 @@ def test_numfig_with_secnum_depth_warn(app, warning): app.build() warnings = warning.getvalue() assert 'index.rst:47: WARNING: numfig is disabled. :numref: is ignored.' not in warnings - assert 'index.rst:55: WARNING: no number is assigned for section: index' in warnings + assert 'index.rst:55: WARNING: Failed to create a cross reference. Any number is not assigned: index' in warnings assert 'index.rst:56: WARNING: invalid numfig_format: invalid' in warnings assert 'index.rst:57: WARNING: invalid numfig_format: Fig %s %s' in warnings
v3.3 upgrade started generating "WARNING: no number is assigned for table" warnings We've updated to Sphinx 3.3 in our documentation, and suddenly the following warning started popping up in our builds when we build either `singlehtml` or `latex`.: `WARNING: no number is assigned for table:` I looked through the changelog but it didn't seem like there was anything related to `numref` that was changed, but perhaps I missed something? Could anyone point me to a change in the numref logic so I can figure out where these warnings are coming from?
I digged into this a little bit more and it seems like the `id` of the table isn't properly making it into `env.toc_fignumbers`. If I set `:name: mylabel`, regardless the I see something like this in `env.toc_fignumbers` ``` 'pagename': {'table': {'id3': (1,)}, ``` So it seems like `id3` is being used for the table id instead of `mylabel` @choldgraf I suspect it's related to this: https://github.com/sphinx-doc/sphinx/commit/66dda1fc50249e9da62e79380251d8795b8e36df. Oooohhh good find! 👏👏👏 Confirmed that this was the issue - we had been referencing Tables that didn't have a title with `numref`, and this bugfix (I guess it was a bugfix?) caused us to start raising errors. Perhaps this restriction about tables needing a title could be documented more clearly? The `numfig` option has been described as follows. >If true, figures, tables and code-blocks are automatically numbered if they have a caption. https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-numfig It says a table not having a title is not assigned a number. Then `numfig` can't refer it because of no table number. > It says a table not having a title is not assigned a number. Then `numfig` can't refer it because of no table number. This means that a user is not able to add a numbered table with no caption correct? I could understand such restrictions for Jupyter Book but it doesn't make a lot of sense for Sphinx IMO. I think Sphinx should allow users to have enumerable nodes with no caption. What do you think @choldgraf? >This means that a user is not able to add a numbered table with no caption correct? Yes. Since the beginning, numfig feature only supports captioned figures and tables. I don't know how many people want to assign numbers to non-captioned items. But this is the first feature request, AFAIK. I think my take is that I don't think it is super useful to be able to have numbered references for things that don't have titles/captions. However, it also didn't feel like it *shouldn't* be possible, and so I assumed that it was possible (and thus ran into what I thought was a bug). I think it would be more helpful to surface a more informative warning like "You attempted to add a numbered reference to a Table without a title, add a title for this to work." (or, surface this gotcha in the documentation more obviously like with a `warning` or `note` directive?) @tk0miya @choldgraf both make good points for restricting `figure` and `table` directives with no caption. My issue is that this is done at the enumerable node which implies that **all** enumerable nodes with no title/caption are skipped - not just `figure` and `table`. > Since the beginning, numfig feature only supports captioned figures and tables. Just to clarify, `numfig` feature has - prior to v3.3.0 - supported uncaptioned tables but it did not display the caption. The user was able to reference the table using `numref` role (see example below). In the event that the user tried to reference the caption (aka `name` placeholder), Sphinx threw a warning indicating that there was no caption. This solution seemed sensible to me because it allowed other extensions to utilize enumerable nodes regardless of caption/no caption restriction. My main motivation for wanting to revert back or restrict the bugfix to tables and figures is because both the extensions I've worked on depend on the utilization of enumerable nodes regardless of captions/no captions. I think it wouldn't be too difficult to add the information to `env.toc_fignumbers` but I wanted to make a case before I addressed this in [sphinx-proof](https://github.com/executablebooks/sphinx-proof) and [sphinx-exercise](https://github.com/executablebooks/sphinx-exercise). **Example** Sphinx Version - v3.2.1 ````md ```{list-table} :header-rows: 1 :name: table1 * - Training - Validation * - 0 - 5 * - 13720 - 2744 ``` Referencing table using `numref`: {numref}`table1`. ```{list-table} Caption here :header-rows: 1 :name: table2 * - Training - Validation * - 0 - 5 * - 13720 - 2744 ``` Referencing table using `numref`: {numref}`table2`. ```` <img width="286" alt="Screen Shot 2020-11-10 at 1 13 15 PM" src="https://user-images.githubusercontent.com/33075058/98672880-c8ebfa80-2356-11eb-820f-8c192fcfe1d8.png"> So it sounds like the `tl;dr` from @najuzilu is that in other extensions, she is *using* the fact that you can reference non-captioned elements with a number, and that Sphinx now removing this ability is breaking those extensions. Is that right? That's correct @choldgraf This is a screenshot of the PDF that is generated from @najuzilu 's example with v3.2.1. As you see, it does not work correctly in LaTeX output. <img width="689" alt="スクリーンショット 2020-11-23 0 44 49" src="https://user-images.githubusercontent.com/748828/99908313-42a3c100-2d25-11eb-9350-ce74e12ef375.png"> I'd not like to support assigning numbers to no captioned items until fixed this (if somebody needs it).
2020-11-22T16:24:25Z
3.4
["tests/test_build_html.py::test_numfig_without_numbered_toctree_warn", "tests/test_build_html.py::test_numfig_with_numbered_toctree_warn", "tests/test_build_html.py::test_numfig_with_prefix_warn", "tests/test_build_html.py::test_numfig_with_secnum_depth_warn"]
["tests/test_build_html.py::test_html4_output", "tests/test_build_html.py::test_html5_output[images.html-expect0]", "tests/test_build_html.py::test_html5_output[images.html-expect1]", "tests/test_build_html.py::test_html5_output[images.html-expect2]", "tests/test_build_html.py::test_html5_output[images.html-expect3]", "tests/test_build_html.py::test_html5_output[images.html-expect4]", "tests/test_build_html.py::test_html5_output[subdir/images.html-expect5]", "tests/test_build_html.py::test_html5_output[subdir/images.html-expect6]", "tests/test_build_html.py::test_html5_output[subdir/includes.html-expect7]", "tests/test_build_html.py::test_html5_output[subdir/includes.html-expect8]", "tests/test_build_html.py::test_html5_output[subdir/includes.html-expect9]", "tests/test_build_html.py::test_html5_output[subdir/includes.html-expect10]", "tests/test_build_html.py::test_html5_output[subdir/includes.html-expect11]", "tests/test_build_html.py::test_html5_output[includes.html-expect12]", "tests/test_build_html.py::test_html5_output[includes.html-expect13]", "tests/test_build_html.py::test_html5_output[includes.html-expect14]", "tests/test_build_html.py::test_html5_output[includes.html-expect15]", "tests/test_build_html.py::test_html5_output[includes.html-expect16]", "tests/test_build_html.py::test_html5_output[includes.html-expect17]", "tests/test_build_html.py::test_html5_output[includes.html-expect18]", "tests/test_build_html.py::test_html5_output[includes.html-expect19]", "tests/test_build_html.py::test_html5_output[includes.html-expect20]", "tests/test_build_html.py::test_html5_output[includes.html-expect21]", "tests/test_build_html.py::test_html5_output[includes.html-expect22]", "tests/test_build_html.py::test_html5_output[includes.html-expect23]", "tests/test_build_html.py::test_html5_output[includes.html-expect24]", "tests/test_build_html.py::test_html5_output[autodoc.html-expect25]", "tests/test_build_html.py::test_html5_output[autodoc.html-expect26]", "tests/test_build_html.py::test_html5_output[autodoc.html-expect27]", "tests/test_build_html.py::test_html5_output[autodoc.html-expect28]", "tests/test_build_html.py::test_html5_output[extapi.html-expect29]", "tests/test_build_html.py::test_html5_output[markup.html-expect30]", "tests/test_build_html.py::test_html5_output[markup.html-expect31]", "tests/test_build_html.py::test_html5_output[markup.html-expect32]", "tests/test_build_html.py::test_html5_output[markup.html-expect33]", "tests/test_build_html.py::test_html5_output[markup.html-expect34]", "tests/test_build_html.py::test_html5_output[markup.html-expect35]", "tests/test_build_html.py::test_html5_output[markup.html-expect36]", "tests/test_build_html.py::test_html5_output[markup.html-expect37]", "tests/test_build_html.py::test_html5_output[markup.html-expect38]", "tests/test_build_html.py::test_html5_output[markup.html-expect39]", "tests/test_build_html.py::test_html5_output[markup.html-expect40]", "tests/test_build_html.py::test_html5_output[markup.html-expect41]", "tests/test_build_html.py::test_html5_output[markup.html-expect42]", "tests/test_build_html.py::test_html5_output[markup.html-expect43]", "tests/test_build_html.py::test_html5_output[markup.html-expect44]", "tests/test_build_html.py::test_html5_output[markup.html-expect45]", "tests/test_build_html.py::test_html5_output[markup.html-expect46]", "tests/test_build_html.py::test_html5_output[markup.html-expect47]", "tests/test_build_html.py::test_html5_output[markup.html-expect48]", "tests/test_build_html.py::test_html5_output[markup.html-expect49]", "tests/test_build_html.py::test_html5_output[markup.html-expect50]", "tests/test_build_html.py::test_html5_output[markup.html-expect51]", "tests/test_build_html.py::test_html5_output[markup.html-expect52]", "tests/test_build_html.py::test_html5_output[markup.html-expect53]", "tests/test_build_html.py::test_html5_output[markup.html-expect54]", "tests/test_build_html.py::test_html5_output[markup.html-expect55]", "tests/test_build_html.py::test_html5_output[markup.html-expect56]", "tests/test_build_html.py::test_html5_output[markup.html-expect57]", "tests/test_build_html.py::test_html5_output[markup.html-expect58]", "tests/test_build_html.py::test_html5_output[markup.html-expect59]", "tests/test_build_html.py::test_html5_output[markup.html-expect60]", "tests/test_build_html.py::test_html5_output[markup.html-expect61]", "tests/test_build_html.py::test_html5_output[markup.html-expect62]", "tests/test_build_html.py::test_html5_output[markup.html-expect63]", "tests/test_build_html.py::test_html5_output[markup.html-expect64]", "tests/test_build_html.py::test_html5_output[markup.html-expect66]", "tests/test_build_html.py::test_html5_output[markup.html-expect67]", "tests/test_build_html.py::test_html5_output[markup.html-expect68]", "tests/test_build_html.py::test_html5_output[markup.html-expect69]", "tests/test_build_html.py::test_html5_output[markup.html-expect70]", "tests/test_build_html.py::test_html5_output[markup.html-expect71]", "tests/test_build_html.py::test_html5_output[markup.html-expect72]", "tests/test_build_html.py::test_html5_output[markup.html-expect73]", "tests/test_build_html.py::test_html5_output[markup.html-expect74]", "tests/test_build_html.py::test_html5_output[markup.html-expect75]", "tests/test_build_html.py::test_html5_output[markup.html-expect76]", "tests/test_build_html.py::test_html5_output[markup.html-expect77]", "tests/test_build_html.py::test_html5_output[markup.html-expect78]", "tests/test_build_html.py::test_html5_output[markup.html-expect80]", "tests/test_build_html.py::test_html5_output[markup.html-expect81]", "tests/test_build_html.py::test_html5_output[markup.html-expect82]", "tests/test_build_html.py::test_html5_output[markup.html-expect83]", "tests/test_build_html.py::test_html5_output[markup.html-expect84]", "tests/test_build_html.py::test_html5_output[markup.html-expect85]", "tests/test_build_html.py::test_html5_output[objects.html-expect86]", "tests/test_build_html.py::test_html5_output[objects.html-expect87]", "tests/test_build_html.py::test_html5_output[objects.html-expect88]", "tests/test_build_html.py::test_html5_output[objects.html-expect89]", "tests/test_build_html.py::test_html5_output[objects.html-expect90]", "tests/test_build_html.py::test_html5_output[objects.html-expect91]", "tests/test_build_html.py::test_html5_output[objects.html-expect92]", "tests/test_build_html.py::test_html5_output[objects.html-expect93]", "tests/test_build_html.py::test_html5_output[objects.html-expect94]", "tests/test_build_html.py::test_html5_output[objects.html-expect95]", "tests/test_build_html.py::test_html5_output[objects.html-expect96]", "tests/test_build_html.py::test_html5_output[objects.html-expect97]", "tests/test_build_html.py::test_html5_output[objects.html-expect98]", "tests/test_build_html.py::test_html5_output[objects.html-expect99]", "tests/test_build_html.py::test_html5_output[objects.html-expect100]", "tests/test_build_html.py::test_html5_output[objects.html-expect101]", "tests/test_build_html.py::test_html5_output[objects.html-expect102]", "tests/test_build_html.py::test_html5_output[objects.html-expect103]", "tests/test_build_html.py::test_html5_output[objects.html-expect104]", "tests/test_build_html.py::test_html5_output[objects.html-expect105]", "tests/test_build_html.py::test_html5_output[objects.html-expect106]", "tests/test_build_html.py::test_html5_output[objects.html-expect107]", "tests/test_build_html.py::test_html5_output[objects.html-expect108]", "tests/test_build_html.py::test_html5_output[objects.html-expect109]", "tests/test_build_html.py::test_html5_output[objects.html-expect110]", "tests/test_build_html.py::test_html5_output[objects.html-expect111]", "tests/test_build_html.py::test_html5_output[objects.html-expect112]", "tests/test_build_html.py::test_html5_output[objects.html-expect113]", "tests/test_build_html.py::test_html5_output[objects.html-expect114]", "tests/test_build_html.py::test_html5_output[objects.html-expect115]", "tests/test_build_html.py::test_html5_output[objects.html-expect116]", "tests/test_build_html.py::test_html5_output[objects.html-expect117]", "tests/test_build_html.py::test_html5_output[objects.html-expect118]", "tests/test_build_html.py::test_html5_output[objects.html-expect119]", "tests/test_build_html.py::test_html5_output[objects.html-expect120]", "tests/test_build_html.py::test_html5_output[objects.html-expect121]", "tests/test_build_html.py::test_html5_output[objects.html-expect122]", "tests/test_build_html.py::test_html5_output[objects.html-expect123]", "tests/test_build_html.py::test_html5_output[objects.html-expect124]", "tests/test_build_html.py::test_html5_output[objects.html-expect125]", "tests/test_build_html.py::test_html5_output[objects.html-expect126]", "tests/test_build_html.py::test_html5_output[objects.html-expect127]", "tests/test_build_html.py::test_html5_output[objects.html-expect128]", "tests/test_build_html.py::test_html5_output[objects.html-expect129]", "tests/test_build_html.py::test_html5_output[objects.html-expect130]", "tests/test_build_html.py::test_html5_output[objects.html-expect131]", "tests/test_build_html.py::test_html5_output[objects.html-expect132]", "tests/test_build_html.py::test_html5_output[index.html-expect133]", "tests/test_build_html.py::test_html5_output[index.html-expect134]", "tests/test_build_html.py::test_html5_output[index.html-expect137]", "tests/test_build_html.py::test_html5_output[index.html-expect138]", "tests/test_build_html.py::test_html5_output[index.html-expect139]", "tests/test_build_html.py::test_html5_output[index.html-expect140]", "tests/test_build_html.py::test_html5_output[index.html-expect141]", "tests/test_build_html.py::test_html5_output[index.html-expect142]", "tests/test_build_html.py::test_html5_output[index.html-expect143]", "tests/test_build_html.py::test_html5_output[index.html-expect144]", "tests/test_build_html.py::test_html5_output[index.html-expect145]", "tests/test_build_html.py::test_html5_output[index.html-expect146]", "tests/test_build_html.py::test_html5_output[index.html-expect147]", "tests/test_build_html.py::test_html5_output[index.html-expect148]", "tests/test_build_html.py::test_html5_output[bom.html-expect149]", "tests/test_build_html.py::test_html5_output[extensions.html-expect150]", "tests/test_build_html.py::test_html5_output[extensions.html-expect151]", "tests/test_build_html.py::test_html5_output[extensions.html-expect152]", "tests/test_build_html.py::test_html5_output[genindex.html-expect153]", "tests/test_build_html.py::test_html5_output[genindex.html-expect154]", "tests/test_build_html.py::test_html5_output[genindex.html-expect155]", "tests/test_build_html.py::test_html5_output[genindex.html-expect156]", "tests/test_build_html.py::test_html5_output[genindex.html-expect157]", "tests/test_build_html.py::test_html5_output[otherext.html-expect173]", "tests/test_build_html.py::test_html5_output[otherext.html-expect174]", "tests/test_build_html.py::test_html_parallel", "tests/test_build_html.py::test_html_download", "tests/test_build_html.py::test_html_download_role", "tests/test_build_html.py::test_html_translator", "tests/test_build_html.py::test_tocdepth[index.html-expect0]", "tests/test_build_html.py::test_tocdepth[index.html-expect1]", "tests/test_build_html.py::test_tocdepth[index.html-expect2]", "tests/test_build_html.py::test_tocdepth[index.html-expect3]", "tests/test_build_html.py::test_tocdepth[foo.html-expect4]", "tests/test_build_html.py::test_tocdepth[foo.html-expect5]", "tests/test_build_html.py::test_tocdepth[foo.html-expect6]", "tests/test_build_html.py::test_tocdepth[foo.html-expect7]", "tests/test_build_html.py::test_tocdepth[foo.html-expect8]", "tests/test_build_html.py::test_tocdepth[foo.html-expect9]", "tests/test_build_html.py::test_tocdepth[foo.html-expect10]", "tests/test_build_html.py::test_tocdepth[foo.html-expect11]", "tests/test_build_html.py::test_tocdepth[foo.html-expect12]", "tests/test_build_html.py::test_tocdepth[foo.html-expect13]", "tests/test_build_html.py::test_tocdepth[foo.html-expect14]", "tests/test_build_html.py::test_tocdepth[foo.html-expect15]", "tests/test_build_html.py::test_tocdepth[foo.html-expect16]", "tests/test_build_html.py::test_tocdepth[foo.html-expect17]", "tests/test_build_html.py::test_tocdepth[bar.html-expect18]", "tests/test_build_html.py::test_tocdepth[bar.html-expect19]", "tests/test_build_html.py::test_tocdepth[bar.html-expect20]", "tests/test_build_html.py::test_tocdepth[bar.html-expect21]", "tests/test_build_html.py::test_tocdepth[bar.html-expect22]", "tests/test_build_html.py::test_tocdepth[bar.html-expect23]", "tests/test_build_html.py::test_tocdepth[bar.html-expect24]", "tests/test_build_html.py::test_tocdepth[bar.html-expect25]", "tests/test_build_html.py::test_tocdepth[bar.html-expect26]", "tests/test_build_html.py::test_tocdepth[bar.html-expect27]", "tests/test_build_html.py::test_tocdepth[bar.html-expect28]", "tests/test_build_html.py::test_tocdepth[bar.html-expect29]", "tests/test_build_html.py::test_tocdepth[baz.html-expect30]", "tests/test_build_html.py::test_tocdepth[baz.html-expect31]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect0]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect1]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect2]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect3]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect4]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect5]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect6]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect7]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect8]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect9]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect10]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect11]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect12]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect13]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect14]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect15]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect16]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect17]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect18]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect19]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect20]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect21]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect22]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect23]", "tests/test_build_html.py::test_tocdepth_singlehtml[index.html-expect24]", "tests/test_build_html.py::test_numfig_disabled_warn", "tests/test_build_html.py::test_numfig_disabled[index.html-expect0]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect1]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect2]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect3]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect4]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect5]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect6]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect7]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect8]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect9]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect10]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect11]", "tests/test_build_html.py::test_numfig_disabled[index.html-expect12]", "tests/test_build_html.py::test_numfig_disabled[foo.html-expect13]", "tests/test_build_html.py::test_numfig_disabled[foo.html-expect14]", "tests/test_build_html.py::test_numfig_disabled[foo.html-expect15]", "tests/test_build_html.py::test_numfig_disabled[bar.html-expect16]", "tests/test_build_html.py::test_numfig_disabled[bar.html-expect17]", "tests/test_build_html.py::test_numfig_disabled[bar.html-expect18]", "tests/test_build_html.py::test_numfig_disabled[baz.html-expect19]", "tests/test_build_html.py::test_numfig_disabled[baz.html-expect20]", "tests/test_build_html.py::test_numfig_disabled[baz.html-expect21]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect2]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect3]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect4]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect5]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect6]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect7]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect8]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect9]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect10]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect11]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect12]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect13]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect14]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[index.html-expect15]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[foo.html-expect20]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[foo.html-expect21]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[foo.html-expect22]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[foo.html-expect23]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[foo.html-expect24]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[foo.html-expect25]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[foo.html-expect26]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[foo.html-expect27]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[bar.html-expect31]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[bar.html-expect32]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[bar.html-expect33]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[bar.html-expect34]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[bar.html-expect35]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[bar.html-expect36]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[baz.html-expect38]", "tests/test_build_html.py::test_numfig_without_numbered_toctree[baz.html-expect39]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect2]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect3]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect4]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect5]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect6]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect7]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect8]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect9]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect10]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect11]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect12]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect13]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect14]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[index.html-expect15]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[foo.html-expect20]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[foo.html-expect21]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[foo.html-expect22]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[foo.html-expect23]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[foo.html-expect24]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[foo.html-expect25]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[foo.html-expect26]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[foo.html-expect27]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[bar.html-expect31]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[bar.html-expect32]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[bar.html-expect33]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[bar.html-expect34]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[bar.html-expect35]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[bar.html-expect36]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[baz.html-expect38]", "tests/test_build_html.py::test_numfig_with_numbered_toctree[baz.html-expect39]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect2]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect3]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect4]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect5]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect6]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect7]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect8]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect9]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect10]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect11]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect12]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect13]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect14]", "tests/test_build_html.py::test_numfig_with_prefix[index.html-expect15]", "tests/test_build_html.py::test_numfig_with_prefix[foo.html-expect20]", "tests/test_build_html.py::test_numfig_with_prefix[foo.html-expect21]", "tests/test_build_html.py::test_numfig_with_prefix[foo.html-expect22]", "tests/test_build_html.py::test_numfig_with_prefix[foo.html-expect23]", "tests/test_build_html.py::test_numfig_with_prefix[foo.html-expect24]", "tests/test_build_html.py::test_numfig_with_prefix[foo.html-expect25]", "tests/test_build_html.py::test_numfig_with_prefix[foo.html-expect26]", "tests/test_build_html.py::test_numfig_with_prefix[foo.html-expect27]", "tests/test_build_html.py::test_numfig_with_prefix[bar.html-expect31]", "tests/test_build_html.py::test_numfig_with_prefix[bar.html-expect32]", "tests/test_build_html.py::test_numfig_with_prefix[bar.html-expect33]", "tests/test_build_html.py::test_numfig_with_prefix[bar.html-expect34]", "tests/test_build_html.py::test_numfig_with_prefix[bar.html-expect35]", "tests/test_build_html.py::test_numfig_with_prefix[bar.html-expect36]", "tests/test_build_html.py::test_numfig_with_prefix[baz.html-expect38]", "tests/test_build_html.py::test_numfig_with_prefix[baz.html-expect39]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect2]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect3]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect4]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect5]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect6]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect7]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect8]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect9]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect10]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect11]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect12]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect13]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect14]", "tests/test_build_html.py::test_numfig_with_secnum_depth[index.html-expect15]", "tests/test_build_html.py::test_numfig_with_secnum_depth[foo.html-expect20]", "tests/test_build_html.py::test_numfig_with_secnum_depth[foo.html-expect21]", "tests/test_build_html.py::test_numfig_with_secnum_depth[foo.html-expect22]", "tests/test_build_html.py::test_numfig_with_secnum_depth[foo.html-expect23]", "tests/test_build_html.py::test_numfig_with_secnum_depth[foo.html-expect24]", "tests/test_build_html.py::test_numfig_with_secnum_depth[foo.html-expect25]", "tests/test_build_html.py::test_numfig_with_secnum_depth[foo.html-expect26]", "tests/test_build_html.py::test_numfig_with_secnum_depth[foo.html-expect27]", "tests/test_build_html.py::test_numfig_with_secnum_depth[bar.html-expect31]", "tests/test_build_html.py::test_numfig_with_secnum_depth[bar.html-expect32]", "tests/test_build_html.py::test_numfig_with_secnum_depth[bar.html-expect33]", "tests/test_build_html.py::test_numfig_with_secnum_depth[bar.html-expect34]", "tests/test_build_html.py::test_numfig_with_secnum_depth[bar.html-expect35]", "tests/test_build_html.py::test_numfig_with_secnum_depth[bar.html-expect36]", "tests/test_build_html.py::test_numfig_with_secnum_depth[baz.html-expect38]", "tests/test_build_html.py::test_numfig_with_secnum_depth[baz.html-expect39]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect2]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect3]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect4]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect5]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect6]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect7]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect8]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect9]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect10]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect11]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect12]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect13]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect14]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect15]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect20]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect21]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect22]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect23]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect24]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect25]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect26]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect27]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect31]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect32]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect33]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect34]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect35]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect36]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect38]", "tests/test_build_html.py::test_numfig_with_singlehtml[index.html-expect39]", "tests/test_build_html.py::test_enumerable_node[index.html-expect3]", "tests/test_build_html.py::test_enumerable_node[index.html-expect4]", "tests/test_build_html.py::test_enumerable_node[index.html-expect5]", "tests/test_build_html.py::test_enumerable_node[index.html-expect6]", "tests/test_build_html.py::test_enumerable_node[index.html-expect7]", "tests/test_build_html.py::test_enumerable_node[index.html-expect8]", "tests/test_build_html.py::test_enumerable_node[index.html-expect9]", "tests/test_build_html.py::test_html_assets", "tests/test_build_html.py::test_html_copy_source", "tests/test_build_html.py::test_html_sourcelink_suffix", "tests/test_build_html.py::test_html_sourcelink_suffix_same", "tests/test_build_html.py::test_html_sourcelink_suffix_empty", "tests/test_build_html.py::test_html_entity", "tests/test_build_html.py::test_html_inventory", "tests/test_build_html.py::test_html_raw_directive", "tests/test_build_html.py::test_alternate_stylesheets[index.html-expect0]", "tests/test_build_html.py::test_alternate_stylesheets[index.html-expect1]", "tests/test_build_html.py::test_alternate_stylesheets[index.html-expect2]", "tests/test_build_html.py::test_alternate_stylesheets[index.html-expect3]", "tests/test_build_html.py::test_alternate_stylesheets[index.html-expect4]", "tests/test_build_html.py::test_alternate_stylesheets[index.html-expect5]", "tests/test_build_html.py::test_alternate_stylesheets[index.html-expect6]", "tests/test_build_html.py::test_alternate_stylesheets[index.html-expect7]", "tests/test_build_html.py::test_html_style", "tests/test_build_html.py::test_html_remote_images", "tests/test_build_html.py::test_html_sidebar", "tests/test_build_html.py::test_html_manpage[index.html-expect0]", "tests/test_build_html.py::test_html_manpage[index.html-expect1]", "tests/test_build_html.py::test_html_manpage[index.html-expect2]", "tests/test_build_html.py::test_html_baseurl", "tests/test_build_html.py::test_html_baseurl_and_html_file_suffix", "tests/test_build_html.py::test_default_html_math_renderer", "tests/test_build_html.py::test_html_math_renderer_is_mathjax", "tests/test_build_html.py::test_html_math_renderer_is_imgmath", "tests/test_build_html.py::test_html_math_renderer_is_duplicated", "tests/test_build_html.py::test_html_math_renderer_is_duplicated2", "tests/test_build_html.py::test_html_math_renderer_is_chosen", "tests/test_build_html.py::test_html_math_renderer_is_mismatched", "tests/test_build_html.py::test_html_pygments_style_default", "tests/test_build_html.py::test_html_pygments_style_manually", "tests/test_build_html.py::test_html_pygments_for_classic_theme", "tests/test_build_html.py::test_html_dark_pygments_style_default", "tests/test_build_html.py::test_validate_html_extra_path", "tests/test_build_html.py::test_validate_html_static_path", "tests/test_build_html.py::test_html_codeblock_linenos_style_inline"]
3f560cd67239f75840cc7a439ab54d8509c855f6
sphinx-doc/sphinx
sphinx-doc__sphinx-8435
5d8d6275a54f2c5fb72b82383b5712c22d337634
diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py --- a/sphinx/ext/autodoc/__init__.py +++ b/sphinx/ext/autodoc/__init__.py @@ -1702,7 +1702,8 @@ def add_directive_header(self, sig: str) -> None: if not self.options.annotation: # obtain annotation for this data try: - annotations = get_type_hints(self.parent) + annotations = get_type_hints(self.parent, None, + self.config.autodoc_type_aliases) except NameError: # Failed to evaluate ForwardRef (maybe TYPE_CHECKING) annotations = safe_getattr(self.parent, '__annotations__', {}) @@ -2093,7 +2094,8 @@ def add_directive_header(self, sig: str) -> None: if not self.options.annotation: # obtain type annotation for this attribute try: - annotations = get_type_hints(self.parent) + annotations = get_type_hints(self.parent, None, + self.config.autodoc_type_aliases) except NameError: # Failed to evaluate ForwardRef (maybe TYPE_CHECKING) annotations = safe_getattr(self.parent, '__annotations__', {})
diff --git a/tests/roots/test-ext-autodoc/target/annotations.py b/tests/roots/test-ext-autodoc/target/annotations.py --- a/tests/roots/test-ext-autodoc/target/annotations.py +++ b/tests/roots/test-ext-autodoc/target/annotations.py @@ -4,6 +4,9 @@ myint = int +#: docstring +variable: myint + def sum(x: myint, y: myint) -> myint: """docstring""" @@ -23,3 +26,10 @@ def mult(x: float, y: float) -> float: def mult(x, y): """docstring""" return x, y + + +class Foo: + """docstring""" + + #: docstring + attr: myint diff --git a/tests/test_ext_autodoc_configs.py b/tests/test_ext_autodoc_configs.py --- a/tests/test_ext_autodoc_configs.py +++ b/tests/test_ext_autodoc_configs.py @@ -700,6 +700,19 @@ def test_autodoc_type_aliases(app): '.. py:module:: target.annotations', '', '', + '.. py:class:: Foo()', + ' :module: target.annotations', + '', + ' docstring', + '', + '', + ' .. py:attribute:: Foo.attr', + ' :module: target.annotations', + ' :type: int', + '', + ' docstring', + '', + '', '.. py:function:: mult(x: int, y: int) -> int', ' mult(x: float, y: float) -> float', ' :module: target.annotations', @@ -712,6 +725,13 @@ def test_autodoc_type_aliases(app): '', ' docstring', '', + '', + '.. py:data:: variable', + ' :module: target.annotations', + ' :type: int', + '', + ' docstring', + '', ] # define aliases @@ -722,6 +742,19 @@ def test_autodoc_type_aliases(app): '.. py:module:: target.annotations', '', '', + '.. py:class:: Foo()', + ' :module: target.annotations', + '', + ' docstring', + '', + '', + ' .. py:attribute:: Foo.attr', + ' :module: target.annotations', + ' :type: myint', + '', + ' docstring', + '', + '', '.. py:function:: mult(x: myint, y: myint) -> myint', ' mult(x: float, y: float) -> float', ' :module: target.annotations', @@ -734,6 +767,13 @@ def test_autodoc_type_aliases(app): '', ' docstring', '', + '', + '.. py:data:: variable', + ' :module: target.annotations', + ' :type: myint', + '', + ' docstring', + '', ]
# Sphinx autodoc_type_aliases Not Applied to Variables and Attributes ## Issue Description The `autodoc_type_aliases` configuration in Sphinx's autodoc extension is not being applied to module-level variables and class attributes when generating documentation. While this feature successfully resolves type aliases in function parameters and return types, it fails to do the same for variable annotations. This appears to be due to inconsistent handling of type annotations across different documenter classes in the autodoc extension, specifically affecting `DataDocumenter` (for module variables) and `AttributeDocumenter` (for class attributes). ## Reproduction Steps ```python # example.py from __future__ import annotations #: blah blah blah var: String # This annotation should use the alias class MyString: "mystring" #: blah blah blah var: String # This annotation should use the alias ``` ```rst # index.rst .. automodule:: example :members: :undoc-members: ``` ```python # conf.py autodoc_type_aliases = { 'String': 'example.MyString' } ``` When these files are processed by Sphinx with autodoc enabled, the type annotations for both the module-level `var` and the class attribute `MyString.var` will show as `String` rather than being resolved to `example.MyString` as would be expected based on the `autodoc_type_aliases` configuration. Internally, the issue occurs because: 1. The annotation processing flow correctly applies type aliases to function parameters and return types 2. However, the handling for variable and attribute annotations doesn't integrate with the type alias system 3. The code paths for documenting variables differ from those for documenting function signatures ## Expected Behavior The `autodoc_type_aliases` configuration should be applied consistently to all annotated objects, including: - Module-level variables (like `var: String`) - Class attributes (like `MyString.var: String`) - Function parameters and return types (which already work correctly) After type alias resolution, the documentation should show `example.MyString` instead of the raw `String` annotation for both variables. ## Exploration Hints ### Files to Examine: - **sphinx/ext/autodoc/__init__.py** - This is the core autodoc extension module that contains the documenter classes. It implements specialized documenters for different types of Python objects, including `DataDocumenter` for module variables and `AttributeDocumenter` for class attributes, which are both directly involved in the issue. The problem likely stems from these documenter classes not utilizing the type alias registry when formatting annotations. - **sphinx/ext/autodoc/typehints.py** - Contains the type hint processing logic but currently only handles callable objects (functions and methods). It's missing logic to process variable annotations with the same type alias resolution applied to function parameters. - **sphinx/util/inspect.py** - Contains the `format_annotation()` function which is the entry point for converting annotation objects to string representations. This function needs to be aware of the type aliases configuration. ### Key Classes/Functions: - **DataDocumenter** - Responsible for documenting module-level variables. This class needs to incorporate type alias handling when it processes annotations. - **AttributeDocumenter** - Handles class attributes and needs similar updates to process type aliases. - **format_annotation()** - Currently delegates all work to `stringify_annotation()` without passing any context about aliases. This is a key point where type alias resolution should occur. - **stringify_annotation()** - Converts annotation objects to strings but doesn't have access to the type aliases configuration. ### Areas of Interest: - How annotations are formatted in different contexts (variables vs. functions) - The flow of annotation information from Python objects to documentation output - How configuration values like `autodoc_type_aliases` are accessed by utility functions - The interaction between forward references (from `__future__ import annotations`) and type alias resolution ## Fix Hints ### High Confidence Locations: - `DataDocumenter.add_directive_header()` and `AttributeDocumenter.add_directive_header()` in **sphinx/ext/autodoc/__init__.py** - These methods likely need to be updated to properly handle type aliases when processing annotations for variables and attributes. - `format_annotation()` in **sphinx/util/inspect.py** - This function needs to be enhanced to accept and use the `autodoc_type_aliases` configuration when formatting annotations. ### Implementation Hints: - The fix likely requires modifying how annotations are processed in the variable and attribute documenters to use the same type alias resolution mechanism that's already working for function signatures. - Consider creating a unified approach for annotation processing across all documenters: 1. Extend `record_typehints()` in **sphinx/ext/autodoc/typehints.py** to handle non-callable objects 2. Modify `format_annotation()` to accept and utilize type aliases 3. Ensure all documenter classes use this common mechanism - Ensure proper handling of forward references (from `__future__ import annotations`), which may be stored differently than regular annotations. ### Alternative Hypotheses: - The issue may not be in the documenter classes themselves but in how the annotation information is extracted or processed before reaching them, especially when `from __future__ import annotations` is used. - There might be a different mechanism for resolving types of variables vs. function parameters that's not correctly integrated with the type alias system. - The bug could relate to how string-based annotations (which happen with `from __future__ import annotations`) are handled differently than object-based annotations.
2020-11-15T17:12:24Z
3.4
["tests/test_ext_autodoc_configs.py::test_autodoc_type_aliases"]
["tests/test_ext_autodoc_configs.py::test_autoclass_content_class", "tests/test_ext_autodoc_configs.py::test_autoclass_content_init", "tests/test_ext_autodoc_configs.py::test_autoclass_content_both", "tests/test_ext_autodoc_configs.py::test_autodoc_inherit_docstrings", "tests/test_ext_autodoc_configs.py::test_autodoc_docstring_signature", "tests/test_ext_autodoc_configs.py::test_autoclass_content_and_docstring_signature_class", "tests/test_ext_autodoc_configs.py::test_autoclass_content_and_docstring_signature_init", "tests/test_ext_autodoc_configs.py::test_autoclass_content_and_docstring_signature_both", "tests/test_ext_autodoc_configs.py::test_mocked_module_imports", "tests/test_ext_autodoc_configs.py::test_autodoc_typehints_signature", "tests/test_ext_autodoc_configs.py::test_autodoc_typehints_none", "tests/test_ext_autodoc_configs.py::test_autodoc_typehints_none_for_overload", "tests/test_ext_autodoc_configs.py::test_autodoc_typehints_description", "tests/test_ext_autodoc_configs.py::test_autodoc_typehints_description_for_invalid_node", "tests/test_ext_autodoc_configs.py::test_autodoc_default_options", "tests/test_ext_autodoc_configs.py::test_autodoc_default_options_with_values"]
3f560cd67239f75840cc7a439ab54d8509c855f6
pydata/xarray
pydata__xarray-4493
a5f53e203c52a7605d5db799864046471115d04f
diff --git a/xarray/core/variable.py b/xarray/core/variable.py --- a/xarray/core/variable.py +++ b/xarray/core/variable.py @@ -120,6 +120,16 @@ def as_variable(obj, name=None) -> "Union[Variable, IndexVariable]": if isinstance(obj, Variable): obj = obj.copy(deep=False) elif isinstance(obj, tuple): + if isinstance(obj[1], DataArray): + # TODO: change into TypeError + warnings.warn( + ( + "Using a DataArray object to construct a variable is" + " ambiguous, please extract the data using the .data property." + " This will raise a TypeError in 0.19.0." + ), + DeprecationWarning, + ) try: obj = Variable(*obj) except (TypeError, ValueError) as error:
diff --git a/xarray/tests/test_dask.py b/xarray/tests/test_dask.py --- a/xarray/tests/test_dask.py +++ b/xarray/tests/test_dask.py @@ -1233,7 +1233,7 @@ def test_map_blocks_to_array(map_ds): lambda x: x.drop_vars("x"), lambda x: x.expand_dims(k=[1, 2, 3]), lambda x: x.expand_dims(k=3), - lambda x: x.assign_coords(new_coord=("y", x.y * 2)), + lambda x: x.assign_coords(new_coord=("y", x.y.data * 2)), lambda x: x.astype(np.int32), lambda x: x.x, ], diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -4959,13 +4959,13 @@ def test_reduce_keepdims(self): # Coordinates involved in the reduction should be removed actual = ds.mean(keepdims=True) expected = Dataset( - {"a": (["x", "y"], np.mean(ds.a, keepdims=True))}, coords={"c": ds.c} + {"a": (["x", "y"], np.mean(ds.a, keepdims=True).data)}, coords={"c": ds.c} ) assert_identical(expected, actual) actual = ds.mean("x", keepdims=True) expected = Dataset( - {"a": (["x", "y"], np.mean(ds.a, axis=0, keepdims=True))}, + {"a": (["x", "y"], np.mean(ds.a, axis=0, keepdims=True).data)}, coords={"y": ds.y, "c": ds.c}, ) assert_identical(expected, actual) diff --git a/xarray/tests/test_interp.py b/xarray/tests/test_interp.py --- a/xarray/tests/test_interp.py +++ b/xarray/tests/test_interp.py @@ -190,7 +190,7 @@ def func(obj, dim, new_x): "w": xdest["w"], "z2": xdest["z2"], "y": da["y"], - "x": (("z", "w"), xdest), + "x": (("z", "w"), xdest.data), "x2": (("z", "w"), func(da["x2"], "x", xdest)), }, ) diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py --- a/xarray/tests/test_variable.py +++ b/xarray/tests/test_variable.py @@ -8,7 +8,7 @@ import pytest import pytz -from xarray import Coordinate, Dataset, IndexVariable, Variable, set_options +from xarray import Coordinate, DataArray, Dataset, IndexVariable, Variable, set_options from xarray.core import dtypes, duck_array_ops, indexing from xarray.core.common import full_like, ones_like, zeros_like from xarray.core.indexing import ( @@ -1081,6 +1081,9 @@ def test_as_variable(self): td = np.array([timedelta(days=x) for x in range(10)]) assert as_variable(td, "time").dtype.kind == "m" + with pytest.warns(DeprecationWarning): + as_variable(("x", DataArray([]))) + def test_repr(self): v = Variable(["time", "x"], [[1, 2, 3], [4, 5, 6]], {"foo": "bar"}) expected = dedent(
# Enhanced Problem Statement: DataSet.update Causes Chunked Dask DataArray to Evaluate Values Eagerly ## Issue Description When using `Dataset.update()` with a dictionary containing chunked dask DataArrays in the form of tuples like `(dims, data)`, the DataArrays are being eagerly evaluated, converting them to numpy arrays and losing their chunked representation. This behavior is inconsistent with other xarray operations that preserve the chunked nature of dask arrays. The issue specifically occurs when using the tuple format to specify dimensions and data in the update dictionary, while directly using DataArrays in Dataset creation preserves chunking. ## Reproduction Steps ```python # Create a chunked DataArray foo = xr.DataArray(np.random.randn(3, 3), dims=("x", "y")).chunk() # foo is chunked ds = xr.Dataset({"foo": foo, "bar": ("x", [1, 2, 3])}) # foo is still chunked here # Create update dictionary with tuple format (dims, data) update_dict = {"foo": (("x", "y"), ds.foo[1:, :]), "bar": ("x", ds.bar[1:])} # At this point, update_dict["foo"][1] is still a chunked dask array # Apply the update ds.update(update_dict) # Now ds.foo is no longer chunked - it has been converted to a numpy array ``` A similar issue occurs in the Dataset constructor: ```python import dask.array as da import xarray as xr # This maintains chunking x = da.random.randint(1, 10, size=(100, 25)) ds = xr.Dataset(dict(a=xr.DataArray(x, dims=('x', 'y')))) type(ds.a.data) # Output: dask.array.core.Array # This triggers computation ds2 = xr.Dataset(dict(a=(('x', 'y'), ds.a))) type(ds2.a.data) # Output: numpy.ndarray ``` ## Expected Behavior The chunked dask DataArray should remain chunked after the update operation, preserving its lazy evaluation properties. When using the tuple format with dimensions and data in `update_dict`, the chunked nature of the underlying dask array should be preserved, just as it is when directly using DataArrays in Dataset creation. ## Exploration Hints ### Files to Examine: - **xarray/core/dataset.py** - Contains the `Dataset` class and the `update` method that's central to this issue. The problem occurs when processing the update dictionary and creating or updating variables. - **xarray/core/variable.py** - Handles conversion of data into Variables, which are the building blocks of Datasets. The `as_variable()` and `as_compatible_data()` functions may not be properly preserving dask arrays when handling tuple inputs. - **xarray/core/dataarray.py** - Contains the `DataArray` class implementation, which defines how data is stored and accessed. Important for understanding how chunked arrays are handled. ### Key Classes/Functions: - **Dataset.update()** - The method directly responsible for the reported bug. It processes the update dictionary and delegates to `dataset_update_method()` before applying changes via `_replace()`. - **as_variable()** (in variable.py) - Converts different types of inputs into Variables. The issue likely occurs when processing tuples of the form `(dims, data)`. - **as_compatible_data()** (in variable.py) - Determines how input data should be handled, including whether dask arrays should be preserved or computed. ### Areas of Interest: - The conversion path that happens when data is provided as a tuple `(dims, data)` versus when a DataArray is provided directly. - How the dimensions and data are extracted and processed when creating new Variables during the update operation. - How chunking information is preserved (or not preserved) through the chain of function calls during update. - The distinction between Dataset initialization and Dataset update regarding preservation of chunked arrays. ## Fix Hints ### High Confidence Locations: - **as_variable()** in variable.py - This function likely isn't properly preserving dask arrays when processing tuple inputs like `(dims, data)`. It may be extracting the array data from the DataArray without preserving chunking information. ### Implementation Hints: - Ensure that when extracting data from a DataArray that's part of a tuple in the update dictionary, the chunking information is preserved. - Check for any type conversions or array handling in the processing chain that might trigger computation of dask arrays. - Look for places where `.data` is accessed on DataArrays, which might be triggering computation instead of preserving the dask representation. - Ensure that the code path for handling `(dims, data)` tuples treats dask arrays consistently with how direct DataArray inputs are treated. ### Alternative Hypotheses: 1. The issue could be in how slicing operations (`ds.foo[1:, :]`) interact with the update process, potentially modifying metadata related to chunking. 2. There might be dimension validation or alignment checks during update that are triggering computation for explicitly-dimensioned inputs. 3. The problem could be in the `_replace` method that's used internally by Dataset to apply updates, which might handle chunked arrays differently based on how they're provided. 4. There could be an intentional design decision to compute certain values during Dataset updates for consistency or performance reasons, but this behavior is not properly documented. 5. The update process might be correctly preserving the dask structure, but display or inspection methods might be computing values when showing the updated dataset.
that's because `xarray.core.variable.as_compatible_data` doesn't consider `DataArray` objects: https://github.com/pydata/xarray/blob/333e8dba55f0165ccadf18f2aaaee9257a4d716b/xarray/core/variable.py#L202-L203 and thus falls back to `DataArray.values`: https://github.com/pydata/xarray/blob/333e8dba55f0165ccadf18f2aaaee9257a4d716b/xarray/core/variable.py#L219 I think that's a bug and it should be fine to use ```python if isinstance(data, (DataArray, Variable)): return data.data ``` but I didn't check if that would break anything. Are you up for sending in a PR? For now, you can work around that by manually retrieving `data`: ```python In [2]: foo = xr.DataArray(np.random.randn(3, 3), dims=("x", "y")).chunk() # foo is chunked ...: ds = xr.Dataset({"foo": foo, "bar": ("x", [1, 2, 3])}) # foo is still chunked here ...: ds Out[2]: <xarray.Dataset> Dimensions: (x: 3, y: 3) Dimensions without coordinates: x, y Data variables: foo (x, y) float64 dask.array<chunksize=(3, 3), meta=np.ndarray> bar (x) int64 1 2 3 In [3]: ds2 = ds.assign( ...: { ...: "foo": lambda ds: (("x", "y"), ds.foo[1:, :].data), ...: "bar": lambda ds: ("x", ds.bar[1:]), ...: } ...: ) ...: ds2 Out[3]: <xarray.Dataset> Dimensions: (x: 2, y: 3) Dimensions without coordinates: x, y Data variables: foo (x, y) float64 dask.array<chunksize=(2, 3), meta=np.ndarray> bar (x) int64 2 3 ``` > xarray.core.variable.as_compatible_data doesn't consider DataArray objects: I don't think DataArrays are expected at that level though. BUT I'm probably wrong. > {"foo": (("x", "y"), ds.foo[1:, :]), "bar": ("x", ds.bar[1:])} This syntax is weird. You should be able to do `update_dict = {"foo": ds.foo[1:, :], "bar": ds.bar[1:]}` . For the simple example, `ds.update(update_dict)` and `ds.assign(update_dict)` both fail because you can't align dimensions without labels when the dimension size is different between variables (I find this confusing). @chunhochow What are you trying to do? Overwrite the existing `foo` and `bar` variables? > when the dimension size is different between variables (I find this confusing). I guess the issue is that the dataset has `x` at a certain size and by reassigning we're trying to set `x` to a different size. I *think* the failure is expected in this case, and it could be solved by assigning labels to `x`. Thinking about the initial problem some more, it might be better to simply point to `isel`: ```python ds2 = ds.isel(x=slice(1, None)) ds2 ``` should do the same, but without having to worry about manually reconstructing a valid dataset. Yes, I'm trying to drop the last "bin" of data (the edge has problems) along all the DataArrays along the dimension `x`, But I couldn't figure out the syntax for how to do it from reading the documentation. Thank you! I will try `isel` next week when I get back to it!
2020-10-06T22:00:41Z
0.12
["xarray/tests/test_variable.py::TestVariable::test_as_variable"]
["xarray/tests/test_dask.py::test_raise_if_dask_computes", "xarray/tests/test_dask.py::TestVariable::test_basics", "xarray/tests/test_dask.py::TestVariable::test_copy", "xarray/tests/test_dask.py::TestVariable::test_chunk", "xarray/tests/test_dask.py::TestVariable::test_indexing", "xarray/tests/test_dask.py::TestVariable::test_squeeze", "xarray/tests/test_dask.py::TestVariable::test_equals", "xarray/tests/test_dask.py::TestVariable::test_transpose", "xarray/tests/test_dask.py::TestVariable::test_shift", "xarray/tests/test_dask.py::TestVariable::test_roll", "xarray/tests/test_dask.py::TestVariable::test_unary_op", "xarray/tests/test_dask.py::TestVariable::test_binary_op", "xarray/tests/test_dask.py::TestVariable::test_repr", "xarray/tests/test_dask.py::TestVariable::test_pickle", "xarray/tests/test_dask.py::TestVariable::test_reduce", "xarray/tests/test_dask.py::TestVariable::test_missing_values", "xarray/tests/test_dask.py::TestVariable::test_concat", "xarray/tests/test_dask.py::TestVariable::test_missing_methods", "xarray/tests/test_dask.py::TestVariable::test_univariate_ufunc", "xarray/tests/test_dask.py::TestVariable::test_bivariate_ufunc", "xarray/tests/test_dask.py::TestVariable::test_compute", "xarray/tests/test_dask.py::TestVariable::test_persist", "xarray/tests/test_dask.py::TestVariable::test_tokenize_duck_dask_array", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_rechunk", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_new_chunk", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_lazy_dataset", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_lazy_array", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_compute", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_persist", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_concat_loads_variables", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_groupby", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_rolling", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_groupby_first", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_reindex", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_to_dataset_roundtrip", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_merge", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_ufuncs", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_where_dispatching", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_simultaneous_compute", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_stack", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_dot", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_dataarray_repr", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_dataset_repr", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_dataarray_pickle", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_dataset_pickle", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_dataarray_getattr", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_dataset_getattr", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_values", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_from_dask_variable", "xarray/tests/test_dask.py::TestDataArrayAndDataset::test_tokenize_duck_dask_array", "xarray/tests/test_dask.py::TestToDaskDataFrame::test_to_dask_dataframe", "xarray/tests/test_dask.py::TestToDaskDataFrame::test_to_dask_dataframe_2D", "xarray/tests/test_dask.py::TestToDaskDataFrame::test_to_dask_dataframe_coordinates", "xarray/tests/test_dask.py::TestToDaskDataFrame::test_to_dask_dataframe_not_daskarray", "xarray/tests/test_dask.py::TestToDaskDataFrame::test_to_dask_dataframe_no_coordinate", "xarray/tests/test_dask.py::TestToDaskDataFrame::test_to_dask_dataframe_dim_order", "xarray/tests/test_dask.py::test_dask_kwargs_variable[load]", "xarray/tests/test_dask.py::test_dask_kwargs_variable[compute]", "xarray/tests/test_dask.py::test_dask_kwargs_dataarray[load]", "xarray/tests/test_dask.py::test_dask_kwargs_dataarray[compute]", "xarray/tests/test_dask.py::test_dask_kwargs_dataarray[persist]", "xarray/tests/test_dask.py::test_dask_kwargs_dataset[load]", "xarray/tests/test_dask.py::test_dask_kwargs_dataset[compute]", "xarray/tests/test_dask.py::test_dask_kwargs_dataset[persist]", "xarray/tests/test_dask.py::test_persist_Dataset[<lambda>0]", "xarray/tests/test_dask.py::test_persist_DataArray[<lambda>0]", "xarray/tests/test_dask.py::test_persist_DataArray[<lambda>1]", "xarray/tests/test_dask.py::test_dataarray_with_dask_coords", "xarray/tests/test_dask.py::test_basic_compute", "xarray/tests/test_dask.py::test_dask_layers_and_dependencies", "xarray/tests/test_dask.py::test_unify_chunks", "xarray/tests/test_dask.py::test_unify_chunks_shallow_copy[<lambda>0-obj0]", "xarray/tests/test_dask.py::test_unify_chunks_shallow_copy[<lambda>0-obj1]", "xarray/tests/test_dask.py::test_unify_chunks_shallow_copy[<lambda>1-obj0]", "xarray/tests/test_dask.py::test_unify_chunks_shallow_copy[<lambda>1-obj1]", "xarray/tests/test_dask.py::test_auto_chunk_da[obj0]", "xarray/tests/test_dask.py::test_make_meta", "xarray/tests/test_dask.py::test_identical_coords_no_computes", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>0-obj0]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>0-obj1]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>0-obj2]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>0-obj3]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>1-obj0]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>1-obj1]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>1-obj2]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>1-obj3]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>2-obj0]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>2-obj1]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>2-obj2]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>2-obj3]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>3-obj0]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>3-obj1]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>3-obj2]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>3-obj3]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>4-obj0]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>4-obj1]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>4-obj2]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>4-obj3]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>5-obj0]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>5-obj1]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>5-obj2]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>5-obj3]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>6-obj0]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>6-obj1]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>6-obj2]", "xarray/tests/test_dask.py::test_token_changes_on_transform[<lambda>6-obj3]", "xarray/tests/test_dask.py::test_token_changes_when_data_changes[obj0]", "xarray/tests/test_dask.py::test_token_changes_when_data_changes[obj1]", "xarray/tests/test_dask.py::test_token_changes_when_data_changes[obj2]", "xarray/tests/test_dask.py::test_token_changes_when_data_changes[obj3]", "xarray/tests/test_dask.py::test_token_changes_when_buffer_changes[obj0]", "xarray/tests/test_dask.py::test_token_changes_when_buffer_changes[obj1]", "xarray/tests/test_dask.py::test_token_identical[obj0-<lambda>0]", "xarray/tests/test_dask.py::test_token_identical[obj0-<lambda>1]", "xarray/tests/test_dask.py::test_token_identical[obj0-<lambda>2]", "xarray/tests/test_dask.py::test_token_identical[obj1-<lambda>0]", "xarray/tests/test_dask.py::test_token_identical[obj1-<lambda>1]", "xarray/tests/test_dask.py::test_token_identical[obj1-<lambda>2]", "xarray/tests/test_dask.py::test_token_identical[obj2-<lambda>0]", "xarray/tests/test_dask.py::test_token_identical[obj2-<lambda>1]", "xarray/tests/test_dask.py::test_token_identical[obj2-<lambda>2]", "xarray/tests/test_dask.py::test_recursive_token", "xarray/tests/test_dask.py::test_normalize_token_with_backend", "xarray/tests/test_dask.py::test_lazy_array_equiv_variables[broadcast_equals]", "xarray/tests/test_dask.py::test_lazy_array_equiv_variables[equals]", "xarray/tests/test_dask.py::test_lazy_array_equiv_variables[identical]", "xarray/tests/test_dask.py::test_lazy_array_equiv_variables[no_conflicts]", "xarray/tests/test_dask.py::test_lazy_array_equiv_merge[broadcast_equals]", "xarray/tests/test_dask.py::test_lazy_array_equiv_merge[equals]", "xarray/tests/test_dask.py::test_lazy_array_equiv_merge[identical]", "xarray/tests/test_dask.py::test_lazy_array_equiv_merge[no_conflicts]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>0-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>0-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>1-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>1-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>2-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>2-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>3-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>3-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>4-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>4-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>5-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>5-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>6-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>6-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>7-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>7-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>8-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>8-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>9-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>9-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>10-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>10-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>11-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>11-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>12-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>12-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>13-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>13-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>14-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>14-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>15-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>15-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>16-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>16-obj1]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>17-obj0]", "xarray/tests/test_dask.py::test_transforms_pass_lazy_array_equiv[<lambda>17-obj1]", "xarray/tests/test_dask.py::test_more_transforms_pass_lazy_array_equiv", "xarray/tests/test_dask.py::test_optimize", "xarray/tests/test_dataset.py::TestDataset::test_repr", "xarray/tests/test_dataset.py::TestDataset::test_repr_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_repr_period_index", "xarray/tests/test_dataset.py::TestDataset::test_unicode_data", "xarray/tests/test_dataset.py::TestDataset::test_repr_nep18", "xarray/tests/test_dataset.py::TestDataset::test_info", "xarray/tests/test_dataset.py::TestDataset::test_constructor", "xarray/tests/test_dataset.py::TestDataset::test_constructor_invalid_dims", "xarray/tests/test_dataset.py::TestDataset::test_constructor_1d", "xarray/tests/test_dataset.py::TestDataset::test_constructor_0d", "xarray/tests/test_dataset.py::TestDataset::test_constructor_deprecated", "xarray/tests/test_dataset.py::TestDataset::test_constructor_auto_align", "xarray/tests/test_dataset.py::TestDataset::test_constructor_pandas_sequence", "xarray/tests/test_dataset.py::TestDataset::test_constructor_pandas_single", "xarray/tests/test_dataset.py::TestDataset::test_constructor_compat", "xarray/tests/test_dataset.py::TestDataset::test_constructor_with_coords", "xarray/tests/test_dataset.py::TestDataset::test_properties", "xarray/tests/test_dataset.py::TestDataset::test_asarray", "xarray/tests/test_dataset.py::TestDataset::test_get_index", "xarray/tests/test_dataset.py::TestDataset::test_attr_access", "xarray/tests/test_dataset.py::TestDataset::test_variable", "xarray/tests/test_dataset.py::TestDataset::test_modify_inplace", "xarray/tests/test_dataset.py::TestDataset::test_coords_properties", "xarray/tests/test_dataset.py::TestDataset::test_coords_modify", "xarray/tests/test_dataset.py::TestDataset::test_update_index", "xarray/tests/test_dataset.py::TestDataset::test_coords_setitem_with_new_dimension", "xarray/tests/test_dataset.py::TestDataset::test_coords_setitem_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_coords_set", "xarray/tests/test_dataset.py::TestDataset::test_coords_to_dataset", "xarray/tests/test_dataset.py::TestDataset::test_coords_merge", "xarray/tests/test_dataset.py::TestDataset::test_coords_merge_mismatched_shape", "xarray/tests/test_dataset.py::TestDataset::test_data_vars_properties", "xarray/tests/test_dataset.py::TestDataset::test_equals_and_identical", "xarray/tests/test_dataset.py::TestDataset::test_equals_failures", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_equals", "xarray/tests/test_dataset.py::TestDataset::test_attrs", "xarray/tests/test_dataset.py::TestDataset::test_chunk", "xarray/tests/test_dataset.py::TestDataset::test_dask_is_lazy", "xarray/tests/test_dataset.py::TestDataset::test_isel", "xarray/tests/test_dataset.py::TestDataset::test_isel_fancy", "xarray/tests/test_dataset.py::TestDataset::test_isel_dataarray", "xarray/tests/test_dataset.py::TestDataset::test_sel", "xarray/tests/test_dataset.py::TestDataset::test_sel_dataarray", "xarray/tests/test_dataset.py::TestDataset::test_sel_dataarray_mindex", "xarray/tests/test_dataset.py::TestDataset::test_categorical_index", "xarray/tests/test_dataset.py::TestDataset::test_categorical_reindex", "xarray/tests/test_dataset.py::TestDataset::test_sel_drop", "xarray/tests/test_dataset.py::TestDataset::test_isel_drop", "xarray/tests/test_dataset.py::TestDataset::test_head", "xarray/tests/test_dataset.py::TestDataset::test_tail", "xarray/tests/test_dataset.py::TestDataset::test_thin", "xarray/tests/test_dataset.py::TestDataset::test_sel_fancy", "xarray/tests/test_dataset.py::TestDataset::test_sel_method", "xarray/tests/test_dataset.py::TestDataset::test_loc", "xarray/tests/test_dataset.py::TestDataset::test_selection_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_like", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like", "xarray/tests/test_dataset.py::TestDataset::test_reindex", "xarray/tests/test_dataset.py::TestDataset::test_reindex_warning", "xarray/tests/test_dataset.py::TestDataset::test_reindex_variables_copied", "xarray/tests/test_dataset.py::TestDataset::test_reindex_method", "xarray/tests/test_dataset.py::TestDataset::test_reindex_fill_value[fill_value0]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_fill_value[2]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_fill_value[2.0]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_fill_value[fill_value3]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like_fill_value[fill_value0]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like_fill_value[2]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like_fill_value[2.0]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like_fill_value[fill_value3]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_str_dtype[str]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_str_dtype[bytes]", "xarray/tests/test_dataset.py::TestDataset::test_align_fill_value[fill_value0]", "xarray/tests/test_dataset.py::TestDataset::test_align_fill_value[2]", "xarray/tests/test_dataset.py::TestDataset::test_align_fill_value[2.0]", "xarray/tests/test_dataset.py::TestDataset::test_align_fill_value[fill_value3]", "xarray/tests/test_dataset.py::TestDataset::test_align", "xarray/tests/test_dataset.py::TestDataset::test_align_exact", "xarray/tests/test_dataset.py::TestDataset::test_align_override", "xarray/tests/test_dataset.py::TestDataset::test_align_exclude", "xarray/tests/test_dataset.py::TestDataset::test_align_nocopy", "xarray/tests/test_dataset.py::TestDataset::test_align_indexes", "xarray/tests/test_dataset.py::TestDataset::test_align_non_unique", "xarray/tests/test_dataset.py::TestDataset::test_align_str_dtype", "xarray/tests/test_dataset.py::TestDataset::test_broadcast", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_nocopy", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_exclude", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_misaligned", "xarray/tests/test_dataset.py::TestDataset::test_variable_indexing", "xarray/tests/test_dataset.py::TestDataset::test_drop_variables", "xarray/tests/test_dataset.py::TestDataset::test_drop_index_labels", "xarray/tests/test_dataset.py::TestDataset::test_drop_labels_by_keyword", "xarray/tests/test_dataset.py::TestDataset::test_drop_labels_by_position", "xarray/tests/test_dataset.py::TestDataset::test_drop_dims", "xarray/tests/test_dataset.py::TestDataset::test_copy", "xarray/tests/test_dataset.py::TestDataset::test_copy_with_data", "xarray/tests/test_dataset.py::TestDataset::test_copy_with_data_errors", "xarray/tests/test_dataset.py::TestDataset::test_rename", "xarray/tests/test_dataset.py::TestDataset::test_rename_old_name", "xarray/tests/test_dataset.py::TestDataset::test_rename_same_name", "xarray/tests/test_dataset.py::TestDataset::test_rename_dims", "xarray/tests/test_dataset.py::TestDataset::test_rename_vars", "xarray/tests/test_dataset.py::TestDataset::test_rename_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_rename_does_not_change_CFTimeIndex_type", "xarray/tests/test_dataset.py::TestDataset::test_rename_does_not_change_DatetimeIndex_type", "xarray/tests/test_dataset.py::TestDataset::test_swap_dims", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_error", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_int", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_coords", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_existing_scalar_coord", "xarray/tests/test_dataset.py::TestDataset::test_isel_expand_dims_roundtrip", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_mixed_int_and_coords", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_kwargs_python36plus", "xarray/tests/test_dataset.py::TestDataset::test_set_index", "xarray/tests/test_dataset.py::TestDataset::test_reset_index", "xarray/tests/test_dataset.py::TestDataset::test_reset_index_keep_attrs", "xarray/tests/test_dataset.py::TestDataset::test_reorder_levels", "xarray/tests/test_dataset.py::TestDataset::test_stack", "xarray/tests/test_dataset.py::TestDataset::test_unstack", "xarray/tests/test_dataset.py::TestDataset::test_unstack_errors", "xarray/tests/test_dataset.py::TestDataset::test_unstack_fill_value", "xarray/tests/test_dataset.py::TestDataset::test_unstack_sparse", "xarray/tests/test_dataset.py::TestDataset::test_stack_unstack_fast", "xarray/tests/test_dataset.py::TestDataset::test_stack_unstack_slow", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_invalid_sample_dims", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_name", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_dtype_dims", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_to_unstacked_dataset", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_to_unstacked_dataset_different_dimension", "xarray/tests/test_dataset.py::TestDataset::test_update", "xarray/tests/test_dataset.py::TestDataset::test_update_overwrite_coords", "xarray/tests/test_dataset.py::TestDataset::test_update_auto_align", "xarray/tests/test_dataset.py::TestDataset::test_getitem", "xarray/tests/test_dataset.py::TestDataset::test_getitem_hashable", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variables_default_coords", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variables_time", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variable_same_name", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variable_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_time_season", "xarray/tests/test_dataset.py::TestDataset::test_slice_virtual_variable", "xarray/tests/test_dataset.py::TestDataset::test_setitem", "xarray/tests/test_dataset.py::TestDataset::test_setitem_pandas", "xarray/tests/test_dataset.py::TestDataset::test_setitem_auto_align", "xarray/tests/test_dataset.py::TestDataset::test_setitem_dimension_override", "xarray/tests/test_dataset.py::TestDataset::test_setitem_with_coords", "xarray/tests/test_dataset.py::TestDataset::test_setitem_align_new_indexes", "xarray/tests/test_dataset.py::TestDataset::test_setitem_str_dtype[str]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_str_dtype[bytes]", "xarray/tests/test_dataset.py::TestDataset::test_assign", "xarray/tests/test_dataset.py::TestDataset::test_assign_coords", "xarray/tests/test_dataset.py::TestDataset::test_assign_attrs", "xarray/tests/test_dataset.py::TestDataset::test_assign_multiindex_level", "xarray/tests/test_dataset.py::TestDataset::test_merge_multiindex_level", "xarray/tests/test_dataset.py::TestDataset::test_setitem_original_non_unique_index", "xarray/tests/test_dataset.py::TestDataset::test_setitem_both_non_unique_index", "xarray/tests/test_dataset.py::TestDataset::test_setitem_multiindex_level", "xarray/tests/test_dataset.py::TestDataset::test_delitem", "xarray/tests/test_dataset.py::TestDataset::test_squeeze", "xarray/tests/test_dataset.py::TestDataset::test_squeeze_drop", "xarray/tests/test_dataset.py::TestDataset::test_groupby", "xarray/tests/test_dataset.py::TestDataset::test_groupby_returns_new_type", "xarray/tests/test_dataset.py::TestDataset::test_groupby_iter", "xarray/tests/test_dataset.py::TestDataset::test_groupby_errors", "xarray/tests/test_dataset.py::TestDataset::test_groupby_reduce", "xarray/tests/test_dataset.py::TestDataset::test_groupby_math", "xarray/tests/test_dataset.py::TestDataset::test_groupby_math_virtual", "xarray/tests/test_dataset.py::TestDataset::test_groupby_nan", "xarray/tests/test_dataset.py::TestDataset::test_groupby_order", "xarray/tests/test_dataset.py::TestDataset::test_resample_and_first", "xarray/tests/test_dataset.py::TestDataset::test_resample_min_count", "xarray/tests/test_dataset.py::TestDataset::test_resample_by_mean_with_keep_attrs", "xarray/tests/test_dataset.py::TestDataset::test_resample_loffset", "xarray/tests/test_dataset.py::TestDataset::test_resample_by_mean_discarding_attrs", "xarray/tests/test_dataset.py::TestDataset::test_resample_by_last_discarding_attrs", "xarray/tests/test_dataset.py::TestDataset::test_resample_drop_nondim_coords", "xarray/tests/test_dataset.py::TestDataset::test_resample_old_api", "xarray/tests/test_dataset.py::TestDataset::test_resample_ds_da_are_the_same", "xarray/tests/test_dataset.py::TestDataset::test_ds_resample_apply_func_args", "xarray/tests/test_dataset.py::TestDataset::test_to_array", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dataframe", "xarray/tests/test_dataset.py::TestDataset::test_from_dataframe_sparse", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_empty_dataframe", "xarray/tests/test_dataset.py::TestDataset::test_from_dataframe_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_from_dataframe_unsorted_levels", "xarray/tests/test_dataset.py::TestDataset::test_from_dataframe_non_unique_columns", "xarray/tests/test_dataset.py::TestDataset::test_convert_dataframe_with_many_types_and_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dict", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dict_with_time_dim", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dict_with_nan_nat", "xarray/tests/test_dataset.py::TestDataset::test_to_dict_with_numpy_attrs", "xarray/tests/test_dataset.py::TestDataset::test_pickle", "xarray/tests/test_dataset.py::TestDataset::test_lazy_load", "xarray/tests/test_dataset.py::TestDataset::test_dropna", "xarray/tests/test_dataset.py::TestDataset::test_fillna", "xarray/tests/test_dataset.py::TestDataset::test_propagate_attrs[<lambda>0]", "xarray/tests/test_dataset.py::TestDataset::test_propagate_attrs[<lambda>1]", "xarray/tests/test_dataset.py::TestDataset::test_propagate_attrs[absolute]", "xarray/tests/test_dataset.py::TestDataset::test_propagate_attrs[abs]", "xarray/tests/test_dataset.py::TestDataset::test_where", "xarray/tests/test_dataset.py::TestDataset::test_where_other", "xarray/tests/test_dataset.py::TestDataset::test_where_drop", "xarray/tests/test_dataset.py::TestDataset::test_where_drop_empty", "xarray/tests/test_dataset.py::TestDataset::test_where_drop_no_indexes", "xarray/tests/test_dataset.py::TestDataset::test_reduce", "xarray/tests/test_dataset.py::TestDataset::test_reduce_coords", "xarray/tests/test_dataset.py::TestDataset::test_mean_uint_dtype", "xarray/tests/test_dataset.py::TestDataset::test_reduce_bad_dim", "xarray/tests/test_dataset.py::TestDataset::test_reduce_cumsum", "xarray/tests/test_dataset.py::TestDataset::test_reduce_cumsum_test_dims", "xarray/tests/test_dataset.py::TestDataset::test_reduce_non_numeric", "xarray/tests/test_dataset.py::TestDataset::test_reduce_strings", "xarray/tests/test_dataset.py::TestDataset::test_reduce_dtypes", "xarray/tests/test_dataset.py::TestDataset::test_reduce_keep_attrs", "xarray/tests/test_dataset.py::TestDataset::test_reduce_argmin", "xarray/tests/test_dataset.py::TestDataset::test_reduce_scalars", "xarray/tests/test_dataset.py::TestDataset::test_reduce_only_one_axis", "xarray/tests/test_dataset.py::TestDataset::test_reduce_no_axis", "xarray/tests/test_dataset.py::TestDataset::test_reduce_keepdims", "xarray/tests/test_dataset.py::TestDataset::test_quantile[0.25-True]", "xarray/tests/test_dataset.py::TestDataset::test_quantile[0.25-False]", "xarray/tests/test_dataset.py::TestDataset::test_quantile[q1-True]", "xarray/tests/test_dataset.py::TestDataset::test_quantile[q1-False]", "xarray/tests/test_dataset.py::TestDataset::test_quantile[q2-True]", "xarray/tests/test_dataset.py::TestDataset::test_quantile[q2-False]", "xarray/tests/test_dataset.py::TestDataset::test_quantile_skipna[True]", "xarray/tests/test_dataset.py::TestDataset::test_quantile_skipna[False]", "xarray/tests/test_dataset.py::TestDataset::test_rank", "xarray/tests/test_dataset.py::TestDataset::test_count", "xarray/tests/test_dataset.py::TestDataset::test_map", "xarray/tests/test_dataset.py::TestDataset::test_apply_pending_deprecated_map", "xarray/tests/test_dataset.py::TestDataset::test_dataset_number_math", "xarray/tests/test_dataset.py::TestDataset::test_unary_ops", "xarray/tests/test_dataset.py::TestDataset::test_dataset_array_math", "xarray/tests/test_dataset.py::TestDataset::test_dataset_dataset_math", "xarray/tests/test_dataset.py::TestDataset::test_dataset_math_auto_align", "xarray/tests/test_dataset.py::TestDataset::test_dataset_math_errors", "xarray/tests/test_dataset.py::TestDataset::test_dataset_transpose", "xarray/tests/test_dataset.py::TestDataset::test_dataset_ellipsis_transpose_different_ordered_vars", "xarray/tests/test_dataset.py::TestDataset::test_dataset_retains_period_index_on_transpose", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n1_simple", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n1_label", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n1", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n2", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_exception_n_neg", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_exception_label_str", "xarray/tests/test_dataset.py::TestDataset::test_shift[fill_value0]", "xarray/tests/test_dataset.py::TestDataset::test_shift[2]", "xarray/tests/test_dataset.py::TestDataset::test_shift[2.0]", "xarray/tests/test_dataset.py::TestDataset::test_shift[fill_value3]", "xarray/tests/test_dataset.py::TestDataset::test_roll_coords", "xarray/tests/test_dataset.py::TestDataset::test_roll_no_coords", "xarray/tests/test_dataset.py::TestDataset::test_roll_coords_none", "xarray/tests/test_dataset.py::TestDataset::test_roll_multidim", "xarray/tests/test_dataset.py::TestDataset::test_real_and_imag", "xarray/tests/test_dataset.py::TestDataset::test_setattr_raises", "xarray/tests/test_dataset.py::TestDataset::test_filter_by_attrs", "xarray/tests/test_dataset.py::TestDataset::test_binary_op_propagate_indexes", "xarray/tests/test_dataset.py::TestDataset::test_binary_op_join_setting", "xarray/tests/test_dataset.py::TestDataset::test_full_like", "xarray/tests/test_dataset.py::TestDataset::test_combine_first", "xarray/tests/test_dataset.py::TestDataset::test_sortby", "xarray/tests/test_dataset.py::TestDataset::test_attribute_access", "xarray/tests/test_dataset.py::TestDataset::test_ipython_key_completion", "xarray/tests/test_dataset.py::TestDataset::test_polyfit_output", "xarray/tests/test_dataset.py::TestDataset::test_pad", "xarray/tests/test_dataset.py::TestDataset::test_astype_attrs", "xarray/tests/test_dataset.py::test_isin[test_elements0]", "xarray/tests/test_dataset.py::test_isin[test_elements1]", "xarray/tests/test_dataset.py::test_isin[test_elements2]", "xarray/tests/test_dataset.py::test_isin_dask[test_elements0]", "xarray/tests/test_dataset.py::test_isin_dask[test_elements1]", "xarray/tests/test_dataset.py::test_isin_dask[test_elements2]", "xarray/tests/test_dataset.py::test_isin_dataset", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords0]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords1]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords2]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords3]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords4]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords5]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords6]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords7]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords8]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords9]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords0]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords1]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords2]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords3]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords4]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords5]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords6]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords7]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords8]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords9]", "xarray/tests/test_dataset.py::test_error_message_on_set_supplied", "xarray/tests/test_dataset.py::test_constructor_raises_with_invalid_coords[unaligned_coords0]", "xarray/tests/test_dataset.py::test_dir_expected_attrs[None]", "xarray/tests/test_dataset.py::test_dir_non_string[None]", "xarray/tests/test_dataset.py::test_dir_unicode[None]", "xarray/tests/test_dataset.py::test_coarsen_absent_dims_error[1]", "xarray/tests/test_dataset.py::test_coarsen[1-trim-left-True]", "xarray/tests/test_dataset.py::test_coarsen[1-trim-left-False]", "xarray/tests/test_dataset.py::test_coarsen[1-pad-right-True]", "xarray/tests/test_dataset.py::test_coarsen[1-pad-right-False]", "xarray/tests/test_dataset.py::test_coarsen_coords[1-True]", "xarray/tests/test_dataset.py::test_coarsen_coords[1-False]", "xarray/tests/test_dataset.py::test_coarsen_coords_cftime", "xarray/tests/test_dataset.py::test_coarsen_keep_attrs", "xarray/tests/test_dataset.py::test_rolling_keep_attrs[reduce-argument0]", "xarray/tests/test_dataset.py::test_rolling_keep_attrs[mean-argument1]", "xarray/tests/test_dataset.py::test_rolling_keep_attrs[construct-argument2]", "xarray/tests/test_dataset.py::test_rolling_keep_attrs[count-argument3]", "xarray/tests/test_dataset.py::test_rolling_keep_attrs_deprecated", "xarray/tests/test_dataset.py::test_rolling_properties[1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-sum]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-var]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-max]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-median]", "xarray/tests/test_dataset.py::test_rolling_exp[1]", "xarray/tests/test_dataset.py::test_rolling_exp_keep_attrs[1]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-None-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-None-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-1-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-2-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-2-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-3-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-3-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-None-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-None-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-1-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-2-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-2-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-3-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-3-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-None-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-None-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-1-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-2-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-2-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-3-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-3-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-None-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-None-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-1-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-2-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-2-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-3-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-3-False]", "xarray/tests/test_dataset.py::test_rolling_construct[1-True]", "xarray/tests/test_dataset.py::test_rolling_construct[1-False]", "xarray/tests/test_dataset.py::test_rolling_construct[2-True]", "xarray/tests/test_dataset.py::test_rolling_construct[2-False]", "xarray/tests/test_dataset.py::test_rolling_construct[3-True]", "xarray/tests/test_dataset.py::test_rolling_construct[3-False]", "xarray/tests/test_dataset.py::test_rolling_construct[4-True]", "xarray/tests/test_dataset.py::test_rolling_construct[4-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-False-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[True-sum-None-True-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[True-sum-None-False-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[True-sum-1-True-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[True-sum-1-False-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[True-max-None-True-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[True-max-None-False-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[True-max-1-True-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[True-max-1-False-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[False-sum-None-True-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[False-sum-None-False-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[False-sum-1-True-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[False-sum-1-False-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[False-max-None-True-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[False-max-None-False-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[False-max-1-True-2]", "xarray/tests/test_dataset.py::test_ndrolling_reduce[False-max-1-False-2]", "xarray/tests/test_dataset.py::test_ndrolling_construct[True-nan-True]", "xarray/tests/test_dataset.py::test_ndrolling_construct[True-nan-False]", "xarray/tests/test_dataset.py::test_ndrolling_construct[True-nan-center2]", "xarray/tests/test_dataset.py::test_ndrolling_construct[True-0.0-True]", "xarray/tests/test_dataset.py::test_ndrolling_construct[True-0.0-False]", "xarray/tests/test_dataset.py::test_ndrolling_construct[True-0.0-center2]", "xarray/tests/test_dataset.py::test_ndrolling_construct[False-nan-True]", "xarray/tests/test_dataset.py::test_ndrolling_construct[False-nan-False]", "xarray/tests/test_dataset.py::test_ndrolling_construct[False-nan-center2]", "xarray/tests/test_dataset.py::test_ndrolling_construct[False-0.0-True]", "xarray/tests/test_dataset.py::test_ndrolling_construct[False-0.0-False]", "xarray/tests/test_dataset.py::test_ndrolling_construct[False-0.0-center2]", "xarray/tests/test_dataset.py::test_raise_no_warning_for_nan_in_binary_ops", "xarray/tests/test_dataset.py::test_raise_no_warning_assert_close[2]", "xarray/tests/test_dataset.py::test_differentiate[1-False]", "xarray/tests/test_dataset.py::test_differentiate[2-False]", "xarray/tests/test_dataset.py::test_differentiate_datetime[False]", "xarray/tests/test_dataset.py::test_differentiate_cftime[False]", "xarray/tests/test_dataset.py::test_integrate[True]", "xarray/tests/test_dataset.py::test_integrate[False]", "xarray/tests/test_dataset.py::test_trapz_datetime[np-True]", "xarray/tests/test_dataset.py::test_trapz_datetime[np-False]", "xarray/tests/test_dataset.py::test_trapz_datetime[cftime-True]", "xarray/tests/test_dataset.py::test_trapz_datetime[cftime-False]", "xarray/tests/test_dataset.py::test_no_dict", "xarray/tests/test_dataset.py::test_subclass_slots", "xarray/tests/test_dataset.py::test_weakref", "xarray/tests/test_dataset.py::test_deepcopy_obj_array", "xarray/tests/test_interp.py::test_keywargs", "xarray/tests/test_interp.py::test_interpolate_1d[0-x-linear]", "xarray/tests/test_interp.py::test_interpolate_1d[0-x-cubic]", "xarray/tests/test_interp.py::test_interpolate_1d[0-y-linear]", "xarray/tests/test_interp.py::test_interpolate_1d[0-y-cubic]", "xarray/tests/test_interp.py::test_interpolate_1d[1-x-linear]", "xarray/tests/test_interp.py::test_interpolate_1d[1-x-cubic]", "xarray/tests/test_interp.py::test_interpolate_1d[1-y-linear]", "xarray/tests/test_interp.py::test_interpolate_1d[1-y-cubic]", "xarray/tests/test_interp.py::test_interpolate_1d_methods[cubic]", "xarray/tests/test_interp.py::test_interpolate_1d_methods[zero]", "xarray/tests/test_interp.py::test_interpolate_vectorize[False]", "xarray/tests/test_interp.py::test_interpolate_vectorize[True]", "xarray/tests/test_interp.py::test_interpolate_nd[3]", "xarray/tests/test_interp.py::test_interpolate_nd[4]", "xarray/tests/test_interp.py::test_interpolate_nd_nd", "xarray/tests/test_interp.py::test_interpolate_nd_with_nan", "xarray/tests/test_interp.py::test_interpolate_scalar[0-linear]", "xarray/tests/test_interp.py::test_interpolate_scalar[1-linear]", "xarray/tests/test_interp.py::test_interpolate_nd_scalar[3-linear]", "xarray/tests/test_interp.py::test_interpolate_nd_scalar[4-linear]", "xarray/tests/test_interp.py::test_nans[True]", "xarray/tests/test_interp.py::test_nans[False]", "xarray/tests/test_interp.py::test_errors[True]", "xarray/tests/test_interp.py::test_errors[False]", "xarray/tests/test_interp.py::test_dtype", "xarray/tests/test_interp.py::test_sorted", "xarray/tests/test_interp.py::test_dimension_wo_coords", "xarray/tests/test_interp.py::test_dataset", "xarray/tests/test_interp.py::test_interpolate_dimorder[0]", "xarray/tests/test_interp.py::test_interpolate_dimorder[3]", "xarray/tests/test_interp.py::test_interp_like", "xarray/tests/test_interp.py::test_datetime[x_new0-expected0]", "xarray/tests/test_interp.py::test_datetime[x_new1-expected1]", "xarray/tests/test_interp.py::test_datetime[x_new2-expected2]", "xarray/tests/test_interp.py::test_datetime[x_new3-expected3]", "xarray/tests/test_interp.py::test_datetime[x_new4-0.5]", "xarray/tests/test_interp.py::test_datetime_single_string", "xarray/tests/test_interp.py::test_cftime", "xarray/tests/test_interp.py::test_cftime_type_error", "xarray/tests/test_interp.py::test_cftime_list_of_strings", "xarray/tests/test_interp.py::test_cftime_single_string", "xarray/tests/test_interp.py::test_datetime_to_non_datetime_error", "xarray/tests/test_interp.py::test_cftime_to_non_cftime_error", "xarray/tests/test_interp.py::test_datetime_interp_noerror", "xarray/tests/test_interp.py::test_3641", "xarray/tests/test_interp.py::test_decompose[nearest]", "xarray/tests/test_interp.py::test_decompose[linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-0-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[1-1-1-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-0-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-1-1-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-0-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-1-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[2-2-2-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-0-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-1-1-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-0-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-1-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-2-2-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-0-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-1-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-2-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-True-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-True-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-True-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-True-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-True-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-True-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-False-linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-False-nearest]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-False-zero]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-False-slinear]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-False-quadratic]", "xarray/tests/test_interp.py::test_interpolate_chunk_1d[3-3-3-False-cubic]", "xarray/tests/test_interp.py::test_interpolate_chunk_advanced[linear]", "xarray/tests/test_interp.py::test_interpolate_chunk_advanced[nearest]", "xarray/tests/test_variable.py::TestVariable::test_properties", "xarray/tests/test_variable.py::TestVariable::test_attrs", "xarray/tests/test_variable.py::TestVariable::test_getitem_dict", "xarray/tests/test_variable.py::TestVariable::test_getitem_1d", "xarray/tests/test_variable.py::TestVariable::test_getitem_1d_fancy", "xarray/tests/test_variable.py::TestVariable::test_getitem_with_mask", "xarray/tests/test_variable.py::TestVariable::test_getitem_with_mask_size_zero", "xarray/tests/test_variable.py::TestVariable::test_getitem_with_mask_nd_indexer", "xarray/tests/test_variable.py::TestVariable::test_index_0d_int", "xarray/tests/test_variable.py::TestVariable::test_index_0d_float", "xarray/tests/test_variable.py::TestVariable::test_index_0d_string", "xarray/tests/test_variable.py::TestVariable::test_index_0d_datetime", "xarray/tests/test_variable.py::TestVariable::test_index_0d_timedelta64", "xarray/tests/test_variable.py::TestVariable::test_index_0d_not_a_time", "xarray/tests/test_variable.py::TestVariable::test_index_0d_object", "xarray/tests/test_variable.py::TestVariable::test_0d_object_array_with_list", "xarray/tests/test_variable.py::TestVariable::test_index_and_concat_datetime", "xarray/tests/test_variable.py::TestVariable::test_0d_time_data", "xarray/tests/test_variable.py::TestVariable::test_datetime64_conversion", "xarray/tests/test_variable.py::TestVariable::test_timedelta64_conversion", "xarray/tests/test_variable.py::TestVariable::test_object_conversion", "xarray/tests/test_variable.py::TestVariable::test_datetime64_valid_range", "xarray/tests/test_variable.py::TestVariable::test_pandas_data", "xarray/tests/test_variable.py::TestVariable::test_pandas_period_index", "xarray/tests/test_variable.py::TestVariable::test_1d_math", "xarray/tests/test_variable.py::TestVariable::test_1d_reduce", "xarray/tests/test_variable.py::TestVariable::test_array_interface", "xarray/tests/test_variable.py::TestVariable::test___array__", "xarray/tests/test_variable.py::TestVariable::test_equals_all_dtypes", "xarray/tests/test_variable.py::TestVariable::test_eq_all_dtypes", "xarray/tests/test_variable.py::TestVariable::test_encoding_preserved", "xarray/tests/test_variable.py::TestVariable::test_concat", "xarray/tests/test_variable.py::TestVariable::test_concat_attrs", "xarray/tests/test_variable.py::TestVariable::test_concat_fixed_len_str", "xarray/tests/test_variable.py::TestVariable::test_concat_number_strings", "xarray/tests/test_variable.py::TestVariable::test_concat_mixed_dtypes", "xarray/tests/test_variable.py::TestVariable::test_copy[float-True]", "xarray/tests/test_variable.py::TestVariable::test_copy[float-False]", "xarray/tests/test_variable.py::TestVariable::test_copy[int-True]", "xarray/tests/test_variable.py::TestVariable::test_copy[int-False]", "xarray/tests/test_variable.py::TestVariable::test_copy[str-True]", "xarray/tests/test_variable.py::TestVariable::test_copy[str-False]", "xarray/tests/test_variable.py::TestVariable::test_copy_index", "xarray/tests/test_variable.py::TestVariable::test_copy_with_data", "xarray/tests/test_variable.py::TestVariable::test_copy_with_data_errors", "xarray/tests/test_variable.py::TestVariable::test_copy_index_with_data", "xarray/tests/test_variable.py::TestVariable::test_copy_index_with_data_errors", "xarray/tests/test_variable.py::TestVariable::test_replace", "xarray/tests/test_variable.py::TestVariable::test_real_and_imag", "xarray/tests/test_variable.py::TestVariable::test_aggregate_complex", "xarray/tests/test_variable.py::TestVariable::test_pandas_cateogrical_dtype", "xarray/tests/test_variable.py::TestVariable::test_pandas_datetime64_with_tz", "xarray/tests/test_variable.py::TestVariable::test_multiindex", "xarray/tests/test_variable.py::TestVariable::test_load", "xarray/tests/test_variable.py::TestVariable::test_getitem_advanced", "xarray/tests/test_variable.py::TestVariable::test_getitem_uint_1d", "xarray/tests/test_variable.py::TestVariable::test_getitem_uint", "xarray/tests/test_variable.py::TestVariable::test_getitem_0d_array", "xarray/tests/test_variable.py::TestVariable::test_getitem_fancy", "xarray/tests/test_variable.py::TestVariable::test_getitem_error", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg0-np_arg0-mean]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg0-np_arg0-edge]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg0-np_arg0-maximum]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg0-np_arg0-minimum]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg0-np_arg0-symmetric]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg0-np_arg0-wrap]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg1-np_arg1-mean]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg1-np_arg1-edge]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg1-np_arg1-maximum]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg1-np_arg1-minimum]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg1-np_arg1-symmetric]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg1-np_arg1-wrap]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg2-np_arg2-mean]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg2-np_arg2-edge]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg2-np_arg2-maximum]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg2-np_arg2-minimum]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg2-np_arg2-symmetric]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg2-np_arg2-wrap]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg3-np_arg3-mean]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg3-np_arg3-edge]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg3-np_arg3-maximum]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg3-np_arg3-minimum]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg3-np_arg3-symmetric]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg3-np_arg3-wrap]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg4-np_arg4-mean]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg4-np_arg4-edge]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg4-np_arg4-maximum]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg4-np_arg4-minimum]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg4-np_arg4-symmetric]", "xarray/tests/test_variable.py::TestVariable::test_pad[xr_arg4-np_arg4-wrap]", "xarray/tests/test_variable.py::TestVariable::test_pad_constant_values[xr_arg0-np_arg0]", "xarray/tests/test_variable.py::TestVariable::test_pad_constant_values[xr_arg1-np_arg1]", "xarray/tests/test_variable.py::TestVariable::test_pad_constant_values[xr_arg2-np_arg2]", "xarray/tests/test_variable.py::TestVariable::test_pad_constant_values[xr_arg3-np_arg3]", "xarray/tests/test_variable.py::TestVariable::test_pad_constant_values[xr_arg4-np_arg4]", "xarray/tests/test_variable.py::TestVariable::test_rolling_window", "xarray/tests/test_variable.py::TestVariable::test_data_and_values", "xarray/tests/test_variable.py::TestVariable::test_numpy_same_methods", "xarray/tests/test_variable.py::TestVariable::test_datetime64_conversion_scalar", "xarray/tests/test_variable.py::TestVariable::test_timedelta64_conversion_scalar", "xarray/tests/test_variable.py::TestVariable::test_0d_str", "xarray/tests/test_variable.py::TestVariable::test_0d_datetime", "xarray/tests/test_variable.py::TestVariable::test_0d_timedelta", "xarray/tests/test_variable.py::TestVariable::test_equals_and_identical", "xarray/tests/test_variable.py::TestVariable::test_broadcast_equals", "xarray/tests/test_variable.py::TestVariable::test_no_conflicts", "xarray/tests/test_variable.py::TestVariable::test_repr", "xarray/tests/test_variable.py::TestVariable::test_repr_lazy_data", "xarray/tests/test_variable.py::TestVariable::test_detect_indexer_type", "xarray/tests/test_variable.py::TestVariable::test_indexer_type", "xarray/tests/test_variable.py::TestVariable::test_items", "xarray/tests/test_variable.py::TestVariable::test_getitem_basic", "xarray/tests/test_variable.py::TestVariable::test_getitem_with_mask_2d_input", "xarray/tests/test_variable.py::TestVariable::test_isel", "xarray/tests/test_variable.py::TestVariable::test_index_0d_numpy_string", "xarray/tests/test_variable.py::TestVariable::test_indexing_0d_unicode", "xarray/tests/test_variable.py::TestVariable::test_shift[fill_value0]", "xarray/tests/test_variable.py::TestVariable::test_shift[2]", "xarray/tests/test_variable.py::TestVariable::test_shift[2.0]", "xarray/tests/test_variable.py::TestVariable::test_shift2d", "xarray/tests/test_variable.py::TestVariable::test_roll", "xarray/tests/test_variable.py::TestVariable::test_roll_consistency", "xarray/tests/test_variable.py::TestVariable::test_transpose", "xarray/tests/test_variable.py::TestVariable::test_transpose_0d", "xarray/tests/test_variable.py::TestVariable::test_squeeze", "xarray/tests/test_variable.py::TestVariable::test_get_axis_num", "xarray/tests/test_variable.py::TestVariable::test_set_dims", "xarray/tests/test_variable.py::TestVariable::test_set_dims_object_dtype", "xarray/tests/test_variable.py::TestVariable::test_stack", "xarray/tests/test_variable.py::TestVariable::test_stack_errors", "xarray/tests/test_variable.py::TestVariable::test_unstack", "xarray/tests/test_variable.py::TestVariable::test_unstack_errors", "xarray/tests/test_variable.py::TestVariable::test_unstack_2d", "xarray/tests/test_variable.py::TestVariable::test_stack_unstack_consistency", "xarray/tests/test_variable.py::TestVariable::test_broadcasting_math", "xarray/tests/test_variable.py::TestVariable::test_broadcasting_failures", "xarray/tests/test_variable.py::TestVariable::test_inplace_math", "xarray/tests/test_variable.py::TestVariable::test_reduce", "xarray/tests/test_variable.py::TestVariable::test_quantile[None-None-0.25-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[None-None-0.25-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[None-None-q1-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[None-None-q1-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[None-None-q2-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[None-None-q2-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[0-x-0.25-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[0-x-0.25-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[0-x-q1-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[0-x-q1-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[0-x-q2-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[0-x-q2-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis2-dim2-0.25-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis2-dim2-0.25-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis2-dim2-q1-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis2-dim2-q1-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis2-dim2-q2-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis2-dim2-q2-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis3-dim3-0.25-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis3-dim3-0.25-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis3-dim3-q1-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis3-dim3-q1-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis3-dim3-q2-True]", "xarray/tests/test_variable.py::TestVariable::test_quantile[axis3-dim3-q2-False]", "xarray/tests/test_variable.py::TestVariable::test_quantile_dask[1-y-0.25]", "xarray/tests/test_variable.py::TestVariable::test_quantile_dask[1-y-q1]", "xarray/tests/test_variable.py::TestVariable::test_quantile_dask[1-y-q2]", "xarray/tests/test_variable.py::TestVariable::test_quantile_dask[axis1-dim1-0.25]", "xarray/tests/test_variable.py::TestVariable::test_quantile_dask[axis1-dim1-q1]", "xarray/tests/test_variable.py::TestVariable::test_quantile_dask[axis1-dim1-q2]", "xarray/tests/test_variable.py::TestVariable::test_quantile_chunked_dim_error", "xarray/tests/test_variable.py::TestVariable::test_quantile_out_of_bounds[-0.1]", "xarray/tests/test_variable.py::TestVariable::test_quantile_out_of_bounds[1.1]", "xarray/tests/test_variable.py::TestVariable::test_quantile_out_of_bounds[q2]", "xarray/tests/test_variable.py::TestVariable::test_quantile_out_of_bounds[q3]", "xarray/tests/test_variable.py::TestVariable::test_rank_dask_raises", "xarray/tests/test_variable.py::TestVariable::test_rank", "xarray/tests/test_variable.py::TestVariable::test_big_endian_reduce", "xarray/tests/test_variable.py::TestVariable::test_reduce_funcs", "xarray/tests/test_variable.py::TestVariable::test_reduce_keepdims", "xarray/tests/test_variable.py::TestVariable::test_reduce_keepdims_dask", "xarray/tests/test_variable.py::TestVariable::test_reduce_keep_attrs", "xarray/tests/test_variable.py::TestVariable::test_binary_ops_keep_attrs", "xarray/tests/test_variable.py::TestVariable::test_count", "xarray/tests/test_variable.py::TestVariable::test_setitem", "xarray/tests/test_variable.py::TestVariable::test_setitem_fancy", "xarray/tests/test_variable.py::TestVariable::test_coarsen", "xarray/tests/test_variable.py::TestVariable::test_coarsen_2d", "xarray/tests/test_variable.py::TestVariable::test_coarsen_keep_attrs", "xarray/tests/test_variable.py::TestVariableWithDask::test_properties", "xarray/tests/test_variable.py::TestVariableWithDask::test_attrs", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_dict", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_1d", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_with_mask", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_with_mask_size_zero", "xarray/tests/test_variable.py::TestVariableWithDask::test_index_0d_int", "xarray/tests/test_variable.py::TestVariableWithDask::test_index_0d_float", "xarray/tests/test_variable.py::TestVariableWithDask::test_index_0d_string", "xarray/tests/test_variable.py::TestVariableWithDask::test_index_0d_datetime", "xarray/tests/test_variable.py::TestVariableWithDask::test_index_0d_timedelta64", "xarray/tests/test_variable.py::TestVariableWithDask::test_index_0d_not_a_time", "xarray/tests/test_variable.py::TestVariableWithDask::test_index_0d_object", "xarray/tests/test_variable.py::TestVariableWithDask::test_index_and_concat_datetime", "xarray/tests/test_variable.py::TestVariableWithDask::test_0d_time_data", "xarray/tests/test_variable.py::TestVariableWithDask::test_datetime64_conversion", "xarray/tests/test_variable.py::TestVariableWithDask::test_timedelta64_conversion", "xarray/tests/test_variable.py::TestVariableWithDask::test_object_conversion", "xarray/tests/test_variable.py::TestVariableWithDask::test_datetime64_valid_range", "xarray/tests/test_variable.py::TestVariableWithDask::test_pandas_data", "xarray/tests/test_variable.py::TestVariableWithDask::test_pandas_period_index", "xarray/tests/test_variable.py::TestVariableWithDask::test_1d_math", "xarray/tests/test_variable.py::TestVariableWithDask::test_1d_reduce", "xarray/tests/test_variable.py::TestVariableWithDask::test___array__", "xarray/tests/test_variable.py::TestVariableWithDask::test_equals_all_dtypes", "xarray/tests/test_variable.py::TestVariableWithDask::test_encoding_preserved", "xarray/tests/test_variable.py::TestVariableWithDask::test_concat", "xarray/tests/test_variable.py::TestVariableWithDask::test_concat_attrs", "xarray/tests/test_variable.py::TestVariableWithDask::test_concat_fixed_len_str", "xarray/tests/test_variable.py::TestVariableWithDask::test_concat_number_strings", "xarray/tests/test_variable.py::TestVariableWithDask::test_concat_mixed_dtypes", "xarray/tests/test_variable.py::TestVariableWithDask::test_copy[float-True]", "xarray/tests/test_variable.py::TestVariableWithDask::test_copy[float-False]", "xarray/tests/test_variable.py::TestVariableWithDask::test_copy[int-True]", "xarray/tests/test_variable.py::TestVariableWithDask::test_copy[int-False]", "xarray/tests/test_variable.py::TestVariableWithDask::test_copy[str-True]", "xarray/tests/test_variable.py::TestVariableWithDask::test_copy[str-False]", "xarray/tests/test_variable.py::TestVariableWithDask::test_copy_with_data", "xarray/tests/test_variable.py::TestVariableWithDask::test_copy_with_data_errors", "xarray/tests/test_variable.py::TestVariableWithDask::test_copy_index_with_data", "xarray/tests/test_variable.py::TestVariableWithDask::test_copy_index_with_data_errors", "xarray/tests/test_variable.py::TestVariableWithDask::test_replace", "xarray/tests/test_variable.py::TestVariableWithDask::test_real_and_imag", "xarray/tests/test_variable.py::TestVariableWithDask::test_aggregate_complex", "xarray/tests/test_variable.py::TestVariableWithDask::test_pandas_cateogrical_dtype", "xarray/tests/test_variable.py::TestVariableWithDask::test_pandas_datetime64_with_tz", "xarray/tests/test_variable.py::TestVariableWithDask::test_multiindex", "xarray/tests/test_variable.py::TestVariableWithDask::test_load", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_advanced", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_uint_1d", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_uint", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_0d_array", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_error", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg0-np_arg0-mean]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg0-np_arg0-edge]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg0-np_arg0-maximum]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg0-np_arg0-minimum]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg0-np_arg0-symmetric]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg0-np_arg0-wrap]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg1-np_arg1-mean]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg1-np_arg1-edge]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg1-np_arg1-maximum]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg1-np_arg1-minimum]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg1-np_arg1-symmetric]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg1-np_arg1-wrap]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg2-np_arg2-mean]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg2-np_arg2-edge]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg2-np_arg2-maximum]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg2-np_arg2-minimum]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg2-np_arg2-symmetric]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg2-np_arg2-wrap]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg3-np_arg3-mean]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg3-np_arg3-edge]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg3-np_arg3-maximum]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg3-np_arg3-minimum]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg3-np_arg3-symmetric]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg3-np_arg3-wrap]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg4-np_arg4-mean]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg4-np_arg4-edge]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg4-np_arg4-maximum]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg4-np_arg4-minimum]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg4-np_arg4-symmetric]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad[xr_arg4-np_arg4-wrap]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad_constant_values[xr_arg0-np_arg0]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad_constant_values[xr_arg1-np_arg1]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad_constant_values[xr_arg2-np_arg2]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad_constant_values[xr_arg3-np_arg3]", "xarray/tests/test_variable.py::TestVariableWithDask::test_pad_constant_values[xr_arg4-np_arg4]", "xarray/tests/test_variable.py::TestVariableWithDask::test_rolling_window", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_fancy", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_1d_fancy", "xarray/tests/test_variable.py::TestVariableWithDask::test_getitem_with_mask_nd_indexer", "xarray/tests/test_variable.py::TestVariableWithSparse::test_as_sparse", "xarray/tests/test_variable.py::TestIndexVariable::test_properties", "xarray/tests/test_variable.py::TestIndexVariable::test_attrs", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_dict", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_1d", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_1d_fancy", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_with_mask", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_with_mask_size_zero", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_with_mask_nd_indexer", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_int", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_float", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_string", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_datetime", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_timedelta64", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_not_a_time", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_object", "xarray/tests/test_variable.py::TestIndexVariable::test_0d_object_array_with_list", "xarray/tests/test_variable.py::TestIndexVariable::test_index_and_concat_datetime", "xarray/tests/test_variable.py::TestIndexVariable::test_0d_time_data", "xarray/tests/test_variable.py::TestIndexVariable::test_datetime64_conversion", "xarray/tests/test_variable.py::TestIndexVariable::test_timedelta64_conversion", "xarray/tests/test_variable.py::TestIndexVariable::test_object_conversion", "xarray/tests/test_variable.py::TestIndexVariable::test_datetime64_valid_range", "xarray/tests/test_variable.py::TestIndexVariable::test_pandas_data", "xarray/tests/test_variable.py::TestIndexVariable::test_pandas_period_index", "xarray/tests/test_variable.py::TestIndexVariable::test_1d_math", "xarray/tests/test_variable.py::TestIndexVariable::test_1d_reduce", "xarray/tests/test_variable.py::TestIndexVariable::test_array_interface", "xarray/tests/test_variable.py::TestIndexVariable::test___array__", "xarray/tests/test_variable.py::TestIndexVariable::test_equals_all_dtypes", "xarray/tests/test_variable.py::TestIndexVariable::test_eq_all_dtypes", "xarray/tests/test_variable.py::TestIndexVariable::test_encoding_preserved", "xarray/tests/test_variable.py::TestIndexVariable::test_concat", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_attrs", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_fixed_len_str", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_number_strings", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_mixed_dtypes", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[float-True]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[float-False]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[int-True]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[int-False]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[str-True]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[str-False]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy_index", "xarray/tests/test_variable.py::TestIndexVariable::test_copy_with_data", "xarray/tests/test_variable.py::TestIndexVariable::test_copy_with_data_errors", "xarray/tests/test_variable.py::TestIndexVariable::test_copy_index_with_data", "xarray/tests/test_variable.py::TestIndexVariable::test_copy_index_with_data_errors", "xarray/tests/test_variable.py::TestIndexVariable::test_replace", "xarray/tests/test_variable.py::TestIndexVariable::test_real_and_imag", "xarray/tests/test_variable.py::TestIndexVariable::test_aggregate_complex", "xarray/tests/test_variable.py::TestIndexVariable::test_pandas_cateogrical_dtype", "xarray/tests/test_variable.py::TestIndexVariable::test_pandas_datetime64_with_tz", "xarray/tests/test_variable.py::TestIndexVariable::test_multiindex", "xarray/tests/test_variable.py::TestIndexVariable::test_load", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_uint_1d", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_0d_array", "xarray/tests/test_variable.py::TestIndexVariable::test_init", "xarray/tests/test_variable.py::TestIndexVariable::test_to_index", "xarray/tests/test_variable.py::TestIndexVariable::test_multiindex_default_level_names", "xarray/tests/test_variable.py::TestIndexVariable::test_data", "xarray/tests/test_variable.py::TestIndexVariable::test_name", "xarray/tests/test_variable.py::TestIndexVariable::test_level_names", "xarray/tests/test_variable.py::TestIndexVariable::test_get_level_variable", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_periods", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_multiindex", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_str_dtype[str]", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_str_dtype[bytes]", "xarray/tests/test_variable.py::TestIndexVariable::test_coordinate_alias", "xarray/tests/test_variable.py::TestIndexVariable::test_datetime64", "xarray/tests/test_variable.py::TestAsCompatibleData::test_unchanged_types", "xarray/tests/test_variable.py::TestAsCompatibleData::test_converted_types", "xarray/tests/test_variable.py::TestAsCompatibleData::test_masked_array", "xarray/tests/test_variable.py::TestAsCompatibleData::test_datetime", "xarray/tests/test_variable.py::TestAsCompatibleData::test_full_like", "xarray/tests/test_variable.py::TestAsCompatibleData::test_full_like_dask", "xarray/tests/test_variable.py::TestAsCompatibleData::test_zeros_like", "xarray/tests/test_variable.py::TestAsCompatibleData::test_ones_like", "xarray/tests/test_variable.py::TestAsCompatibleData::test_unsupported_type", "xarray/tests/test_variable.py::test_raise_no_warning_for_nan_in_binary_ops", "xarray/tests/test_variable.py::TestBackendIndexing::test_NumpyIndexingAdapter", "xarray/tests/test_variable.py::TestBackendIndexing::test_LazilyOuterIndexedArray", "xarray/tests/test_variable.py::TestBackendIndexing::test_CopyOnWriteArray", "xarray/tests/test_variable.py::TestBackendIndexing::test_MemoryCachedArray", "xarray/tests/test_variable.py::TestBackendIndexing::test_DaskIndexingAdapter"]
1c198a191127c601d091213c4b3292a8bb3054e1
scikit-learn/scikit-learn
scikit-learn__scikit-learn-11040
96a02f3934952d486589dddd3f00b40d5a5ab5f2
diff --git a/sklearn/neighbors/base.py b/sklearn/neighbors/base.py --- a/sklearn/neighbors/base.py +++ b/sklearn/neighbors/base.py @@ -258,6 +258,12 @@ def _fit(self, X): "Expected n_neighbors > 0. Got %d" % self.n_neighbors ) + else: + if not np.issubdtype(type(self.n_neighbors), np.integer): + raise TypeError( + "n_neighbors does not take %s value, " + "enter integer value" % + type(self.n_neighbors)) return self @@ -327,6 +333,17 @@ class from an array representing our data set and ask who's if n_neighbors is None: n_neighbors = self.n_neighbors + elif n_neighbors <= 0: + raise ValueError( + "Expected n_neighbors > 0. Got %d" % + n_neighbors + ) + else: + if not np.issubdtype(type(n_neighbors), np.integer): + raise TypeError( + "n_neighbors does not take %s value, " + "enter integer value" % + type(n_neighbors)) if X is not None: query_is_train = False
diff --git a/sklearn/neighbors/tests/test_neighbors.py b/sklearn/neighbors/tests/test_neighbors.py --- a/sklearn/neighbors/tests/test_neighbors.py +++ b/sklearn/neighbors/tests/test_neighbors.py @@ -18,6 +18,7 @@ from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_in from sklearn.utils.testing import assert_raises +from sklearn.utils.testing import assert_raises_regex from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_warns from sklearn.utils.testing import assert_warns_message @@ -108,6 +109,21 @@ def test_unsupervised_inputs(): assert_array_almost_equal(ind1, ind2) +def test_n_neighbors_datatype(): + # Test to check whether n_neighbors is integer + X = [[1, 1], [1, 1], [1, 1]] + expected_msg = "n_neighbors does not take .*float.* " \ + "value, enter integer value" + msg = "Expected n_neighbors > 0. Got -3" + + neighbors_ = neighbors.NearestNeighbors(n_neighbors=3.) + assert_raises_regex(TypeError, expected_msg, neighbors_.fit, X) + assert_raises_regex(ValueError, msg, + neighbors_.kneighbors, X=X, n_neighbors=-3) + assert_raises_regex(TypeError, expected_msg, + neighbors_.kneighbors, X=X, n_neighbors=3.) + + def test_precomputed(random_state=42): """Tests unsupervised NearestNeighbors with a distance matrix.""" # Note: smaller samples may result in spurious test success
# Enhanced Problem Statement: Float Type Validation Issue in NearestNeighbors n_neighbors Parameter ## Issue Description The `n_neighbors` parameter in scikit-learn's `NearestNeighbors` estimator lacks proper type validation. When a float value (e.g., `3.0`) is provided instead of an integer, the code initially accepts the value, but fails later with a cryptic error message when the value reaches the low-level C implementation in `binary_tree.pxi`. The error occurs because the `NeighborsHeap` initialization in the C extension expects an integer value. This type validation issue appears in both the constructor and when the parameter is passed directly to methods like `kneighbors()`. ## Reproduction Steps ```python from sklearn.neighbors import NearestNeighbors from sklearn.datasets import make_blobs # Create sample data X, y = make_blobs() # Initialize NearestNeighbors with a float for n_neighbors (should be integer) neighbors = NearestNeighbors(n_neighbors=3.) neighbors.fit(X) # This line triggers the error neighbors.kneighbors(X) ``` Results in: ``` ~/checkout/scikit-learn/sklearn/neighbors/binary_tree.pxi in sklearn.neighbors.kd_tree.NeighborsHeap.__init__() TypeError: 'float' object cannot be interpreted as an integer ``` The issue also exists when passing a float value directly to the `kneighbors()` method: ```python neighbors = NearestNeighbors(n_neighbors=3) neighbors.fit(X) neighbors.kneighbors(X, n_neighbors=3.) # Error occurs here ``` Internally, the float value propagates through the API layers until it reaches the C extension code where the `NeighborsHeap` constructor tries to use it as an integer, causing the TypeError. ## Expected Behavior The code should validate the type of `n_neighbors` at initialization or method call and either: 1. Raise a clear, informative error message stating that `n_neighbors` must be an integer, or 2. Automatically cast the float to an integer with an appropriate warning message Either way, the validation should happen early in the execution path rather than allowing the error to occur deep in the C extension code, which produces a less helpful error message for users. ## Exploration Hints ### Files to Examine: - **sklearn/neighbors/base.py** - Contains the base classes for nearest neighbors estimators, including `NeighborsBase` and `KNeighborsMixin`. These classes likely define the core functionality and parameter handling, making this a prime location for adding validation. - **sklearn/neighbors/unsupervised.py** - Contains the `NearestNeighbors` class definition which inherits from multiple mixins. The class passes parameters to parent classes without validation. - **sklearn/neighbors/binary_tree.pxi** - Cython code where the error actually occurs in the `NeighborsHeap.__init__` method which expects an integer parameter. - **sklearn/utils/validation.py** - May contain utility functions for parameter validation that could be used for a consistent fix. ### Key Classes/Functions: - **NeighborsBase.__init__()** - Base class constructor that likely sets the `n_neighbors` parameter but doesn't validate its type. - **KNeighborsMixin.kneighbors()** - Method mentioned in the bug report that also accepts an `n_neighbors` parameter without validation. - **NearestNeighbors.__init__()** - Constructor that passes parameters to parent classes without validation. - **NeighborsHeap.__init__()** - The C extension constructor where the error manifests when it receives a float instead of an integer. ### Areas of Interest: - Parameter validation patterns throughout scikit-learn, particularly for numeric parameters - The inheritance hierarchy of neighbor estimators and where parameter validation should logically occur - Existing validation utilities in scikit-learn that could be leveraged - The docstrings which specify `n_neighbors` as an integer parameter, indicating a gap between documentation and implementation ## Fix Hints ### High Confidence Locations: - **NeighborsBase.__init__()** - The most logical place to add type validation is in the base class constructor, ensuring all derived classes receive proper validation. - **KNeighborsMixin.kneighbors()** - The method should validate its `n_neighbors` parameter when explicitly provided to ensure consistent behavior. ### Implementation Hints: 1. Add validation in the `NeighborsBase.__init__` method: ```python if not isinstance(n_neighbors, (int, np.integer)): raise TypeError("n_neighbors must be an integer, got %s" % type(n_neighbors)) ``` 2. Alternatively, for a more lenient approach, cast to integer with a warning: ```python if isinstance(n_neighbors, float) and n_neighbors.is_integer(): warnings.warn("n_neighbors was cast to int from float %s" % n_neighbors) n_neighbors = int(n_neighbors) elif not isinstance(n_neighbors, (int, np.integer)): raise TypeError("n_neighbors must be an integer, got %s" % type(n_neighbors)) ``` 3. Apply similar validation in the `kneighbors` method to handle cases where the parameter is passed directly to that method. ### Alternative Hypotheses: 1. The issue might affect multiple neighbor-based estimators beyond just `NearestNeighbors`, requiring a broader fix across related classes. 2. There could be other numeric parameters in the neighbors module with similar validation gaps (e.g., `leaf_size`, `radius`). 3. It might be possible to modify the C extension code to handle float values directly, though this would be less ideal than early validation at the Python API level. 4. The issue could be part of a broader pattern of inconsistent parameter validation throughout scikit-learn, suggesting a need for standardized validation approaches.
Hello, I would like to take this as my first issue. Thank you. @amueller I added a simple check for float inputs for n_neighbors in order to throw ValueError if that's the case. @urvang96 Did say he was working on it first @Alfo5123 .. @amueller I think there is a lot of other estimators and Python functions in general where dtype isn't explicitely checked and wrong dtype just raises an exception later on. Take for instance, ```py import numpy as np x = np.array([1]) np.sum(x, axis=1.) ``` which produces, ```py Traceback (most recent call last): File "<stdin>", line 1, in <module> File "lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 1882, in sum out=out, **kwargs) File "lib/python3.6/site-packages/numpy/core/_methods.py", line 32, in _sum return umr_sum(a, axis, dtype, out, keepdims) TypeError: 'float' object cannot be interpreted as an integer ``` so pretty much the same exception as in the original post, with no indications of what is wrong exactly. Here it's straightforward because we only provided one parameter, but the same is true for more complex constructions. So I'm not sure that starting to enforce int/float dtype of parameters, estimator by estimator is a solution here. In general don't think there is a need to do more parameter validation than what is done e.g. in numpy or pandas. If we want to do it, some generic type validation based on annotaitons (e.g. https://github.com/agronholm/typeguard) might be easier but also require more maintenance time and probably harder to implement while Python 2.7 is supported. pandas also doesn't enforce it explicitely BTW, ```python pd.DataFrame([{'a': 1, 'b': 2}]).sum(axis=0.) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "lib/python3.6/site-packages/pandas/core/generic.py", line 7295, in stat_func numeric_only=numeric_only, min_count=min_count) File "lib/python3.6/site-packages/pandas/core/frame.py", line 5695, in _reduce axis = self._get_axis_number(axis) File "lib/python3.6/site-packages/pandas/core/generic.py", line 357, in _get_axis_number .format(axis, type(self))) ValueError: No axis named 0.0 for object type <class 'pandas.core.frame.DataFrame'> ``` @Alfo5123 I claimed the issue first and I was working on it. This is not how the community works. @urvang96 Yes, I understand, my bad. Sorry for the inconvenient. I won't continue on it. @Alfo5123 Thank You. Are to going to close the existing PR?
2018-04-28T07:18:33Z
0.20
["sklearn/neighbors/tests/test_neighbors.py::test_n_neighbors_datatype"]
["sklearn/neighbors/tests/test_neighbors.py::test_unsupervised_kneighbors", "sklearn/neighbors/tests/test_neighbors.py::test_unsupervised_inputs", "sklearn/neighbors/tests/test_neighbors.py::test_precomputed", "sklearn/neighbors/tests/test_neighbors.py::test_precomputed_cross_validation", "sklearn/neighbors/tests/test_neighbors.py::test_unsupervised_radius_neighbors", "sklearn/neighbors/tests/test_neighbors.py::test_kneighbors_classifier", "sklearn/neighbors/tests/test_neighbors.py::test_kneighbors_classifier_float_labels", "sklearn/neighbors/tests/test_neighbors.py::test_kneighbors_classifier_predict_proba", "sklearn/neighbors/tests/test_neighbors.py::test_radius_neighbors_classifier", "sklearn/neighbors/tests/test_neighbors.py::test_radius_neighbors_classifier_when_no_neighbors", "sklearn/neighbors/tests/test_neighbors.py::test_radius_neighbors_classifier_outlier_labeling", "sklearn/neighbors/tests/test_neighbors.py::test_radius_neighbors_classifier_zero_distance", "sklearn/neighbors/tests/test_neighbors.py::test_neighbors_regressors_zero_distance", "sklearn/neighbors/tests/test_neighbors.py::test_radius_neighbors_boundary_handling", "sklearn/neighbors/tests/test_neighbors.py::test_RadiusNeighborsClassifier_multioutput", "sklearn/neighbors/tests/test_neighbors.py::test_kneighbors_classifier_sparse", "sklearn/neighbors/tests/test_neighbors.py::test_KNeighborsClassifier_multioutput", "sklearn/neighbors/tests/test_neighbors.py::test_kneighbors_regressor", "sklearn/neighbors/tests/test_neighbors.py::test_KNeighborsRegressor_multioutput_uniform_weight", "sklearn/neighbors/tests/test_neighbors.py::test_kneighbors_regressor_multioutput", "sklearn/neighbors/tests/test_neighbors.py::test_radius_neighbors_regressor", "sklearn/neighbors/tests/test_neighbors.py::test_RadiusNeighborsRegressor_multioutput_with_uniform_weight", "sklearn/neighbors/tests/test_neighbors.py::test_RadiusNeighborsRegressor_multioutput", "sklearn/neighbors/tests/test_neighbors.py::test_kneighbors_regressor_sparse", "sklearn/neighbors/tests/test_neighbors.py::test_neighbors_iris", "sklearn/neighbors/tests/test_neighbors.py::test_neighbors_digits", "sklearn/neighbors/tests/test_neighbors.py::test_kneighbors_graph", "sklearn/neighbors/tests/test_neighbors.py::test_kneighbors_graph_sparse", "sklearn/neighbors/tests/test_neighbors.py::test_radius_neighbors_graph", "sklearn/neighbors/tests/test_neighbors.py::test_radius_neighbors_graph_sparse", "sklearn/neighbors/tests/test_neighbors.py::test_neighbors_badargs", "sklearn/neighbors/tests/test_neighbors.py::test_neighbors_metrics", "sklearn/neighbors/tests/test_neighbors.py::test_callable_metric", "sklearn/neighbors/tests/test_neighbors.py::test_valid_brute_metric_for_auto_algorithm", "sklearn/neighbors/tests/test_neighbors.py::test_metric_params_interface", "sklearn/neighbors/tests/test_neighbors.py::test_predict_sparse_ball_kd_tree", "sklearn/neighbors/tests/test_neighbors.py::test_non_euclidean_kneighbors", "sklearn/neighbors/tests/test_neighbors.py::test_k_and_radius_neighbors_train_is_not_query", "sklearn/neighbors/tests/test_neighbors.py::test_k_and_radius_neighbors_X_None", "sklearn/neighbors/tests/test_neighbors.py::test_k_and_radius_neighbors_duplicates", "sklearn/neighbors/tests/test_neighbors.py::test_include_self_neighbors_graph", "sklearn/neighbors/tests/test_neighbors.py::test_dtype_convert", "sklearn/neighbors/tests/test_neighbors.py::test_sparse_metric_callable", "sklearn/neighbors/tests/test_neighbors.py::test_pairwise_boolean_distance"]
55bf5d93e5674f13a1134d93a11fd0cd11aabcd1
scikit-learn/scikit-learn
scikit-learn__scikit-learn-10949
3b5abf76597ce6aff76192869f92647c1b5259e7
diff --git a/sklearn/utils/validation.py b/sklearn/utils/validation.py --- a/sklearn/utils/validation.py +++ b/sklearn/utils/validation.py @@ -466,6 +466,12 @@ def check_array(array, accept_sparse=False, accept_large_sparse=True, # not a data type (e.g. a column named dtype in a pandas DataFrame) dtype_orig = None + # check if the object contains several dtypes (typically a pandas + # DataFrame), and store them. If not, store None. + dtypes_orig = None + if hasattr(array, "dtypes") and hasattr(array, "__array__"): + dtypes_orig = np.array(array.dtypes) + if dtype_numeric: if dtype_orig is not None and dtype_orig.kind == "O": # if input is object, convert to float. @@ -581,6 +587,16 @@ def check_array(array, accept_sparse=False, accept_large_sparse=True, if copy and np.may_share_memory(array, array_orig): array = np.array(array, dtype=dtype, order=order) + if (warn_on_dtype and dtypes_orig is not None and + {array.dtype} != set(dtypes_orig)): + # if there was at the beginning some other types than the final one + # (for instance in a DataFrame that can contain several dtypes) then + # some data must have been converted + msg = ("Data with input dtype %s were all converted to %s%s." + % (', '.join(map(str, sorted(set(dtypes_orig)))), array.dtype, + context)) + warnings.warn(msg, DataConversionWarning, stacklevel=3) + return array
diff --git a/sklearn/utils/tests/test_validation.py b/sklearn/utils/tests/test_validation.py --- a/sklearn/utils/tests/test_validation.py +++ b/sklearn/utils/tests/test_validation.py @@ -7,6 +7,7 @@ from itertools import product import pytest +from pytest import importorskip import numpy as np import scipy.sparse as sp from scipy import __version__ as scipy_version @@ -713,6 +714,38 @@ def test_suppress_validation(): assert_raises(ValueError, assert_all_finite, X) +def test_check_dataframe_warns_on_dtype(): + # Check that warn_on_dtype also works for DataFrames. + # https://github.com/scikit-learn/scikit-learn/issues/10948 + pd = importorskip("pandas") + + df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], dtype=object) + assert_warns_message(DataConversionWarning, + "Data with input dtype object were all converted to " + "float64.", + check_array, df, dtype=np.float64, warn_on_dtype=True) + assert_warns(DataConversionWarning, check_array, df, + dtype='numeric', warn_on_dtype=True) + assert_no_warnings(check_array, df, dtype='object', warn_on_dtype=True) + + # Also check that it raises a warning for mixed dtypes in a DataFrame. + df_mixed = pd.DataFrame([['1', 2, 3], ['4', 5, 6]]) + assert_warns(DataConversionWarning, check_array, df_mixed, + dtype=np.float64, warn_on_dtype=True) + assert_warns(DataConversionWarning, check_array, df_mixed, + dtype='numeric', warn_on_dtype=True) + assert_warns(DataConversionWarning, check_array, df_mixed, + dtype=object, warn_on_dtype=True) + + # Even with numerical dtypes, a conversion can be made because dtypes are + # uniformized throughout the array. + df_mixed_numeric = pd.DataFrame([[1., 2, 3], [4., 5, 6]]) + assert_warns(DataConversionWarning, check_array, df_mixed_numeric, + dtype='numeric', warn_on_dtype=True) + assert_no_warnings(check_array, df_mixed_numeric.astype(int), + dtype='numeric', warn_on_dtype=True) + + class DummyMemory(object): def cache(self, func): return func
# Silent DataConversionWarning when using `warn_on_dtype=True` with pandas DataFrame ## Issue Description The `check_array` function in scikit-learn fails to emit a `DataConversionWarning` when converting a pandas DataFrame with `dtype=object` to a numpy array with `dtype=float64`, despite setting `warn_on_dtype=True`. This issue specifically occurs only with pandas DataFrame inputs - the warning mechanism works properly with other array-like inputs such as numpy arrays. The root cause appears to be in how `check_array()` handles DataFrame inputs, where it likely converts the DataFrame to a numpy array before capturing and comparing the original dtype, causing the warning condition to fail. ## Reproduction Steps ```python from sklearn.utils.validation import check_array import pandas as pd df = pd.DataFrame([[1, 2, 3], [2, 3, 4]], dtype=object) checked = check_array(df, warn_on_dtype=True) ``` **Expected**: A `DataConversionWarning` indicating conversion from `object` to `float64` dtype **Actual**: No warning is thrown Internally, what likely happens: 1. `check_array()` detects a DataFrame input 2. The function extracts the DataFrame's values using `.values` or similar method 3. The dtype comparison that triggers the warning doesn't properly capture the original DataFrame's dtype 4. Despite a type conversion occurring (from `object` to `float64`), the warning is never triggered ## Expected Behavior When `warn_on_dtype=True` and a DataFrame with `dtype=object` is passed to `check_array()`, a `DataConversionWarning` should be raised with a message like: ``` DataConversionWarning: Data with input dtype object was converted to float64. ``` This warning should be triggered regardless of whether the input is a numpy array or a pandas DataFrame. ## Exploration Hints ### Files to Examine: - **sklearn/utils/validation.py** - Contains the `check_array()` function which is the direct source of the issue. The function handles array validation, type conversion, and should emit warnings when dtype conversions occur. The special handling for DataFrame inputs appears to bypass the warning mechanism. - **sklearn/utils/tests/test_validation.py** - Contains tests for `check_array()`, including separate tests for DataFrame handling and warning behavior, but seems to lack a combined test for DataFrame inputs with `warn_on_dtype=True`. - **sklearn/exceptions.py** - Defines the `DataConversionWarning` class that should be raised during type conversions. ### Key Functions: - **check_array()** - The core function with the issue. Look specifically at: - How it handles pandas DataFrame inputs vs. numpy arrays - Where it captures the original dtype information - The warning condition logic that should compare original and final dtypes - The order of operations for DataFrame conversion and dtype checking ### Areas of Interest: - The early handling of DataFrame inputs in `check_array()` - likely where original dtype information is lost - The conversion of DataFrames to numpy arrays, which might happen before dtype information is properly captured - The comparison logic for detecting dtype changes (`dtype_orig` vs `array.dtype`) - Potential special handling for pandas objects that bypasses warning mechanisms ## Fix Hints ### High Confidence Locations: - In `check_array()`, look for where `dtype_orig` is set and compare with where DataFrame conversion happens. The fix likely requires capturing the DataFrame's dtype before converting it to a numpy array. - The warning logic likely needs to handle DataFrame inputs differently to properly compare the original and final dtypes. ### Implementation Hints: 1. Add special handling for pandas DataFrames that captures their dtype before conversion: ```python # Before conversion to numpy array if hasattr(array, 'dtype') and hasattr(array, 'iloc'): # Detect pandas DataFrame dtype_orig = array.dtypes[0] # For uniform dtype or handle mixed dtypes case ``` 2. Ensure the dtype comparison logic accounts for both numpy arrays and DataFrames: ```python # When checking for warning condition if warn_on_dtype and dtype_orig is not None and array.dtype != dtype_orig: warnings.warn(...) ``` 3. Add a test case that specifically tests DataFrame inputs with `warn_on_dtype=True` ### Alternative Hypotheses: 1. The conversion of DataFrame to numpy array might happen at a lower level (in pandas or numpy) before scikit-learn can detect the dtype change. 2. There might be intentional suppression of warnings for DataFrames that wasn't properly documented. 3. The issue could be specific to how pandas represents object dtypes compared to numpy's handling of dtypes. 4. The warning condition might be checking the wrong attributes when comparing original and final dtypes for DataFrames.
2018-04-10T15:30:56Z
0.20
["sklearn/utils/tests/test_validation.py::test_check_dataframe_warns_on_dtype"]
["sklearn/utils/tests/test_validation.py::test_as_float_array", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X0]", "sklearn/utils/tests/test_validation.py::test_as_float_array_nan[X1]", "sklearn/utils/tests/test_validation.py::test_np_matrix", "sklearn/utils/tests/test_validation.py::test_memmap", "sklearn/utils/tests/test_validation.py::test_ordering", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-inf-False]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[asarray-nan-False]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-inf-False]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-allow-nan]", "sklearn/utils/tests/test_validation.py::test_check_array_force_all_finite_valid[csr_matrix-nan-False]", "sklearn/utils/tests/test_validation.py::test_check_array", "sklearn/utils/tests/test_validation.py::test_check_array_pandas_dtype_object_conversion", "sklearn/utils/tests/test_validation.py::test_check_array_on_mock_dataframe", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_stability", "sklearn/utils/tests/test_validation.py::test_check_array_dtype_warning", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_type_exception", "sklearn/utils/tests/test_validation.py::test_check_array_accept_sparse_no_exception", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csr]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[csc]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[coo]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_no_exception[bsr]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csr]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[csc]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[coo]", "sklearn/utils/tests/test_validation.py::test_check_array_accept_large_sparse_raise_exception[bsr]", "sklearn/utils/tests/test_validation.py::test_check_array_large_indices_non_supported_scipy_version[csr]", "sklearn/utils/tests/test_validation.py::test_check_array_large_indices_non_supported_scipy_version[csc]", "sklearn/utils/tests/test_validation.py::test_check_array_large_indices_non_supported_scipy_version[coo]", "sklearn/utils/tests/test_validation.py::test_check_array_large_indices_non_supported_scipy_version[bsr]", "sklearn/utils/tests/test_validation.py::test_check_array_min_samples_and_features_messages", "sklearn/utils/tests/test_validation.py::test_check_array_complex_data_error", "sklearn/utils/tests/test_validation.py::test_has_fit_parameter", "sklearn/utils/tests/test_validation.py::test_check_symmetric", "sklearn/utils/tests/test_validation.py::test_check_is_fitted", "sklearn/utils/tests/test_validation.py::test_check_consistent_length", "sklearn/utils/tests/test_validation.py::test_check_dataframe_fit_attribute", "sklearn/utils/tests/test_validation.py::test_suppress_validation", "sklearn/utils/tests/test_validation.py::test_check_memory", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[True]", "sklearn/utils/tests/test_validation.py::test_check_array_memmap[False]"]
55bf5d93e5674f13a1134d93a11fd0cd11aabcd1
sphinx-doc/sphinx
sphinx-doc__sphinx-8273
88b81a06eb635a1596617f8971fa97a84c069e93
diff --git a/sphinx/builders/manpage.py b/sphinx/builders/manpage.py --- a/sphinx/builders/manpage.py +++ b/sphinx/builders/manpage.py @@ -24,7 +24,7 @@ from sphinx.util import progress_message from sphinx.util.console import darkgreen # type: ignore from sphinx.util.nodes import inline_all_toctrees -from sphinx.util.osutil import make_filename_from_project +from sphinx.util.osutil import ensuredir, make_filename_from_project from sphinx.writers.manpage import ManualPageWriter, ManualPageTranslator @@ -80,7 +80,12 @@ def write(self, *ignored: Any) -> None: docsettings.authors = authors docsettings.section = section - targetname = '%s.%s' % (name, section) + if self.config.man_make_section_directory: + ensuredir(path.join(self.outdir, str(section))) + targetname = '%s/%s.%s' % (section, name, section) + else: + targetname = '%s.%s' % (name, section) + logger.info(darkgreen(targetname) + ' { ', nonl=True) destination = FileOutput( destination_path=path.join(self.outdir, targetname), @@ -115,6 +120,7 @@ def setup(app: Sphinx) -> Dict[str, Any]: app.add_config_value('man_pages', default_man_pages, None) app.add_config_value('man_show_urls', False, None) + app.add_config_value('man_make_section_directory', False, None) return { 'version': 'builtin',
diff --git a/tests/test_build_manpage.py b/tests/test_build_manpage.py --- a/tests/test_build_manpage.py +++ b/tests/test_build_manpage.py @@ -30,6 +30,13 @@ def test_all(app, status, warning): assert 'Footnotes' not in content +@pytest.mark.sphinx('man', testroot='basic', + confoverrides={'man_make_section_directory': True}) +def test_man_make_section_directory(app, status, warning): + app.build() + assert (app.outdir / '1' / 'python.1').exists() + + @pytest.mark.sphinx('man', testroot='directive-code') def test_captioned_code_block(app, status, warning): app.builder.build_all()
# Enhanced Problem Statement: Man Page Section Directories Issue in Sphinx ## Issue Description Sphinx's man page builder (`ManualPageBuilder`) currently places all generated man pages in a flat, single-level directory structure (`<build-dir>/man`). This approach is incompatible with the standard Unix `man` command when using the `MANPATH` environment variable, which expects man pages to be organized in section-specific subdirectories like `man/man1/`, `man/man3/`, etc. The Unix `man` command explicitly searches for man pages in these section-specific directories, making the current output structure unusable with standard man page lookup mechanisms. The core issue is in the `write()` method of the `ManualPageBuilder` class, which doesn't create the section-based directory structure when writing man page files. ## Reproduction Steps 1. Create a Sphinx documentation project with man pages for different sections 2. Configure the `man_pages` setting in `conf.py`, for example: ```python man_pages = [ ('cmd1', 'command1', 'Command 1 description', ['Author'], 1), ('lib1', 'library1', 'Library 1 description', ['Author'], 3) ] ``` 3. Run Sphinx build with the man page builder: `sphinx-build -b man source build/man` 4. Observe that all man pages are placed directly in the `build/man` directory 5. Try to use this directory with `MANPATH` and notice that the `man` command cannot find the pages Internally, the `ManualPageBuilder.write()` method constructs file paths like `outdir/name.section` (e.g., `build/man/command1.1`) instead of `outdir/man{section}/name.section` (e.g., `build/man/man1/command1.1`). This occurs because the destination path is set without considering section subdirectories: ```python destination = FileOutput( destination_path=path.join(self.outdir, targetname), encoding='utf-8') ``` ## Expected Behavior The man page builder should create section-specific subdirectories (`man1`, `man2`, `man3`, etc.) under the output directory and place each generated man page in the appropriate section directory based on its section number. This would result in a directory structure like: ``` build/man/ man1/ command1.1 man3/ library1.3 ``` This structure would be compatible with the standard `man` command when using the `MANPATH` environment variable, allowing users to directly reference the build directory in their `MANPATH` for testing and development. ## Exploration Hints ### Files to Examine: - **sphinx/builders/manpage.py** - The primary file containing the `ManualPageBuilder` class which is responsible for generating man pages. This is where the output path logic needs modification. - **sphinx/writers/manpage.py** - Contains the `ManualPageWriter` class which transforms document content into man page format, though it doesn't handle file placement directly. ### Key Classes/Functions: - **ManualPageBuilder.write()** - This method determines where man pages are written and is the primary location for the fix. It currently creates files in a flat structure rather than organizing them by section. - **ManualPageBuilder.init()** - May need modification to create section subdirectories during initialization. - **ManualPageBuilder.get_target_uri()** - Determines the target URI for man pages, which might need adjustment if internal references need to account for the new directory structure. ### Areas of Interest: - The `man_pages` configuration tuple structure includes the section number (last element), which is already available to the builder and can be used to determine the appropriate section directory. - The `FileOutput` class used for writing files might not automatically create parent directories, so directory creation logic may need to be added. - Backward compatibility considerations for users who might depend on the current flat structure. ## Fix Hints ### High Confidence Locations: - The primary fix should be in the `write()` method of `ManualPageBuilder` (around line 97-99), where the destination path is set. Instead of: ```python destination = FileOutput( destination_path=path.join(self.outdir, targetname), encoding='utf-8') ``` It should create section directories and place files in them: ```python section_dir = path.join(self.outdir, f"man{section}") os.makedirs(section_dir, exist_ok=True) destination = FileOutput( destination_path=path.join(section_dir, targetname), encoding='utf-8') ``` ### Implementation Hints: - Consider adding a configuration option to control this behavior, allowing users to choose between the standard section-based directory structure and the legacy flat structure for backward compatibility. - The section directories should be created if they don't exist before writing files (using `os.makedirs()` with `exist_ok=True`). - Ensure that any internal references between man pages are updated if they assume a flat directory structure. - The fix is relatively straightforward as the section information is already available in the code, but backward compatibility considerations are important. ### Alternative Hypotheses: - The issue could be addressed in the installation/deployment process rather than the build process, but this wouldn't solve the problem for users who want to test their documentation directly from the build directory. - Some external tools or workflows might expect the current flat structure, which is why a configuration option for backward compatibility would be valuable. - There might be platform-specific considerations for how man pages are organized on different Unix-like systems, though the section directory structure is fairly standard. - The issue might be more complex if cross-references between man pages need to be updated to account for the new directory structure.
I think that users should copy the generated man file to the appropriate directory. The build directory is not an appropriate directory to manage man pages. So no section directory is needed, AFAIK. I don't know why do you want to set `MANPATH` to the output directory. To check the output, you can give the path to the man file for man command like `man _build/man/sphinx-build.1`. Please let me know your purpose in detail. From a [separate github thread](https://github.com/flux-framework/flux-core/pull/3033#issuecomment-662515605) that describes the specific use case in some more detail: > When run in a builddir, `src/cmd/flux` sets `MANPATH` such that `man flux` will display the current builddir version of `flux.1`. This is done so that documentation matches the version of Flux being run. Essentially, we are trying to make running in-tree look as similar to running an installed version as possible. --- > I think that users should copy the generated man file to the appropriate directory. On `make install`, we do have the automake setup to copy the manpages to `$prefix/man/man1`, `$prefix/man/man3`, etc. This did require some extra work though, since each source file and its destination has to be explicitly enumerated in the automake file. If the man pages were built into their respective sections, a recursive copy would work too. Not a huge deal, but just another factor I wanted to bring up. Understandable. +1 to change the structure of output directory. As commented, it causes a breaking change for users. So I propose you to add a configuration `man_make_section_directory = (True | False)` for migration. During 3.x, it defaults to False, and it will default to True on 4.0 release. What do you think? >I’m happy to take a crack at implementing a fix, though this change in behavior may break some people who expect everything to appear in a man/ directory. It would be very nice if you send us a PR :-)
2020-10-03T13:31:13Z
3.3
["tests/test_build_manpage.py::test_man_make_section_directory"]
["tests/test_build_manpage.py::test_all", "tests/test_build_manpage.py::test_default_man_pages", "tests/test_build_manpage.py::test_rubric"]
3b85187ffa3401e88582073c23188c147857a8a3
sympy/sympy
sympy__sympy-12171
ca6ef27272be31c9dc3753ede9232c39df9a75d8
diff --git a/sympy/printing/mathematica.py b/sympy/printing/mathematica.py --- a/sympy/printing/mathematica.py +++ b/sympy/printing/mathematica.py @@ -109,6 +109,9 @@ def _print_Integral(self, expr): def _print_Sum(self, expr): return "Hold[Sum[" + ', '.join(self.doprint(a) for a in expr.args) + "]]" + def _print_Derivative(self, expr): + return "Hold[D[" + ', '.join(self.doprint(a) for a in expr.args) + "]]" + def mathematica_code(expr, **settings): r"""Converts an expr to a string of the Wolfram Mathematica code
diff --git a/sympy/printing/tests/test_mathematica.py b/sympy/printing/tests/test_mathematica.py --- a/sympy/printing/tests/test_mathematica.py +++ b/sympy/printing/tests/test_mathematica.py @@ -1,5 +1,5 @@ from sympy.core import (S, pi, oo, symbols, Function, - Rational, Integer, Tuple) + Rational, Integer, Tuple, Derivative) from sympy.integrals import Integral from sympy.concrete import Sum from sympy.functions import exp, sin, cos @@ -74,6 +74,14 @@ def test_Integral(): "{y, -Infinity, Infinity}]]" +def test_Derivative(): + assert mcode(Derivative(sin(x), x)) == "Hold[D[Sin[x], x]]" + assert mcode(Derivative(x, x)) == "Hold[D[x, x]]" + assert mcode(Derivative(sin(x)*y**4, x, 2)) == "Hold[D[y^4*Sin[x], x, x]]" + assert mcode(Derivative(sin(x)*y**4, x, y, x)) == "Hold[D[y^4*Sin[x], x, y, x]]" + assert mcode(Derivative(sin(x)*y**4, x, y, 3, x)) == "Hold[D[y^4*Sin[x], x, y, y, y, x]]" + + def test_Sum(): assert mcode(Sum(sin(x), (x, 0, 10))) == "Hold[Sum[Sin[x], {x, 0, 10}]]" assert mcode(Sum(exp(-x**2 - y**2),
# Enhanced Problem Statement: Mathematica Code Printer Issues with Derivatives and Float Exponents ## Issue Description The SymPy Mathematica code printer (`MCodePrinter` class) currently fails to correctly handle two important mathematical constructs: 1. **Derivatives**: When printing expressions containing derivatives such as `Derivative(f(t), t)`, the output incorrectly remains in SymPy's internal format instead of being converted to Mathematica's syntax `D[f[t], t]`. This prevents proper usage of the expressions in Mathematica environments. 2. **Floating-point exponents**: Scientific notation in floating-point numbers (e.g., `1.0e-4`) is not properly converted to Mathematica's required format (`1.0*^-4`). This causes numerical values to be interpreted incorrectly when transferring expressions to Mathematica. Both issues stem from missing specialized printer methods in the `MCodePrinter` class that would handle these specific cases. ## Reproduction Steps To reproduce the issues: ```python from sympy import symbols, Function, Derivative from sympy.printing import mathematica_code # Derivative issue t = symbols('t') f = Function('f') derivative_expr = Derivative(f(t), t) print(mathematica_code(derivative_expr)) # Outputs: Derivative(f(t), t) # Expected: D[f[t], t] # Float exponent issue float_value = 1.0e-4 print(mathematica_code(float_value)) # Outputs: 1.0e-4 # Expected: 1.0*^-4 ``` Internally, when the `mathematica_code()` function processes these expressions, it creates an instance of the `MCodePrinter` class and calls its `doprint()` method. Without specific handlers for derivatives and floating-point numbers, the printer falls back to default string representations which do not conform to Mathematica's syntax requirements. ## Expected Behavior The Mathematica code printer should: 1. Convert derivatives like `Derivative(f(t), t)` to Mathematica's syntax: `D[f[t], t]` 2. Convert floating-point numbers with scientific notation like `1.0e-4` to Mathematica's format: `1.0*^-4` This would allow SymPy expressions to be properly transferred to and used in Mathematica environments without manual syntax adjustments. ## Exploration Hints ### Files to Examine: - **sympy/printing/mathematica.py** - Contains the `MCodePrinter` class that needs to be modified. This is where the printer-specific methods for handling different types of mathematical expressions are defined. - **sympy/printing/tests/test_mathematica.py** - Contains tests for the Mathematica printer but lacks tests for derivatives and floating-point exponent handling, explaining why these bugs weren't caught. - **sympy/core/function.py** - Contains the `Derivative` class definition, which helps understand how derivatives are internally represented in SymPy and how they should be printed. ### Key Classes/Functions: - **MCodePrinter** - This is the printer class responsible for converting SymPy expressions to Mathematica syntax. It needs two additional methods to handle the reported issues. - **mathematica_code()** - The public API function that users call to convert SymPy expressions to Mathematica syntax, which internally uses the `MCodePrinter`. - **Derivative** - The SymPy class that represents derivatives internally. Understanding its structure helps implement proper printing. ### Areas of Interest: - The printer follows a visitor pattern where specific types are handled by corresponding `_print_TypeName` methods. - Other printer implementations in SymPy (like LaTeX, Pretty, Str) have dedicated methods for handling derivatives and floats, which could serve as references. - The Mathematica printer handles many other mathematical constructs correctly but is missing specific handlers for derivatives and floating-point exponents. ## Fix Hints ### High Confidence Locations: - **sympy/printing/mathematica.py** in the `MCodePrinter` class, after other `_print_*` methods (around line 93) - This is where the two new methods need to be added. ### Implementation Hints: The proposed solution is straightforward: ```python def _print_Derivative(self, expr): return "D[%s]" % (self.stringify(expr.args, ", ")) def _print_Float(self, expr): res = str(expr) return res.replace('e', '*^') ``` These implementations should work for the basic cases described in the issue: - `_print_Derivative` extracts the arguments from the derivative expression and formats them according to Mathematica's `D[expr, var]` syntax. - `_print_Float` converts the float to a string and replaces 'e' with '*^' to match Mathematica's scientific notation. ### Alternative Hypotheses: 1. The simple string replacement for floats might not handle all edge cases, such as when 'e' appears elsewhere in the string or in very complex floating-point representations. 2. The derivative printing might need more sophisticated handling for: - Higher-order derivatives (e.g., `D[f[t], {t, 2}]` for second derivatives) - Mixed partial derivatives involving multiple variables - Derivatives of complex expressions or nested derivatives 3. There might be other mathematical constructs beyond derivatives and floats that have similar Mathematica-specific syntax requirements not currently being handled correctly. 4. Additional tests should be added to ensure these cases are properly handled and to prevent regression in the future.
I would like to work on this issue So, should I add the lines in printing/mathematica.py ? I've tested the above code by adding these methods to a class derived from MCodePrinter and I was able to export an ODE system straight to NDSolve in Mathematica. So I guess simply adding them to MCodePrinter in in printing/mathematica.py would fix the issue
2017-02-13T18:20:56Z
1.0
["test_Derivative"]
["test_Integer", "test_Rational", "test_Function", "test_Pow", "test_Mul", "test_constants", "test_containers", "test_Integral"]
50b81f9f6be151014501ffac44e5dc6b2416938f
sympy/sympy
sympy__sympy-13043
a3389a25ec84d36f5cf04a4f2562d820f131db64
diff --git a/sympy/integrals/intpoly.py b/sympy/integrals/intpoly.py --- a/sympy/integrals/intpoly.py +++ b/sympy/integrals/intpoly.py @@ -556,7 +556,7 @@ def decompose(expr, separate=False): >>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5) {1: x + y, 2: x**2 + x*y, 5: x**3*y**2 + y**5} >>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5, True) - [x, y, x**2, y**5, x*y, x**3*y**2] + {x, x**2, y, y**5, x*y, x**3*y**2} """ expr = S(expr) poly_dict = {} @@ -569,7 +569,7 @@ def decompose(expr, separate=False): degrees = [(sum(degree_list(monom, *symbols)), monom) for monom in expr.args] if separate: - return [monom[1] for monom in degrees] + return {monom[1] for monom in degrees} else: for monom in degrees: degree, term = monom @@ -593,7 +593,7 @@ def decompose(expr, separate=False): poly_dict[0] = expr if separate: - return list(poly_dict.values()) + return set(poly_dict.values()) return poly_dict
diff --git a/sympy/integrals/tests/test_intpoly.py b/sympy/integrals/tests/test_intpoly.py --- a/sympy/integrals/tests/test_intpoly.py +++ b/sympy/integrals/tests/test_intpoly.py @@ -26,15 +26,15 @@ def test_decompose(): assert decompose(9*x**2 + y + 4*x + x**3 + y**2*x + 3) ==\ {0: 3, 1: 4*x + y, 2: 9*x**2, 3: x**3 + x*y**2} - assert decompose(x, True) == [x] - assert decompose(x ** 2, True) == [x ** 2] - assert decompose(x * y, True) == [x * y] - assert decompose(x + y, True) == [x, y] - assert decompose(x ** 2 + y, True) == [y, x ** 2] - assert decompose(8 * x ** 2 + 4 * y + 7, True) == [7, 4*y, 8*x**2] - assert decompose(x ** 2 + 3 * y * x, True) == [x ** 2, 3 * x * y] + assert decompose(x, True) == {x} + assert decompose(x ** 2, True) == {x**2} + assert decompose(x * y, True) == {x * y} + assert decompose(x + y, True) == {x, y} + assert decompose(x ** 2 + y, True) == {y, x ** 2} + assert decompose(8 * x ** 2 + 4 * y + 7, True) == {7, 4*y, 8*x**2} + assert decompose(x ** 2 + 3 * y * x, True) == {x ** 2, 3 * x * y} assert decompose(9 * x ** 2 + y + 4 * x + x ** 3 + y ** 2 * x + 3, True) == \ - [3, y, x**3, 4*x, 9*x**2, x*y**2] + {3, y, 4*x, 9*x**2, x*y**2, x**3} def test_best_origin():
# Enhanced Problem Statement: Arbitrary Order in decompose() Function Return Values ## Issue Description The `decompose()` function in `sympy/integrals/intpoly.py` returns a list with arbitrary ordering when called with the `separate=True` parameter. Specifically, it returns `list(poly_dict.values())` without any guaranteed ordering of elements. This is causing test failures after recent changes to the core codebase, as tests appear to expect a consistent, deterministic ordering of the returned components. The issue stems from relying on Python dictionary value ordering, which is implementation-dependent, especially in versions prior to Python 3.7 when dictionary ordering wasn't guaranteed to be preserved. ## Reproduction Steps 1. Call the `decompose()` function with `separate=True` parameter 2. Observe that the returned list has elements in arbitrary order 3. This leads to test failures in test cases that expect a specific ordering, such as: ```python assert decompose(8 * x ** 2 + 4 * y + 7, True) == [7, 4*y, 8*x**2] ``` 4. Internally, what happens is: - The function decomposes polynomials into a dictionary with degree as keys - When `separate=True`, it simply returns `list(poly_dict.values())` - No sorting is applied, so ordering depends on dictionary implementation ## Expected Behavior The `decompose()` function should return values in a consistent, deterministic order when `separate=True` is used. Based on the test file, it appears the intended behavior is to return polynomial terms ordered by increasing degree (lowest to highest). Alternatively, if order truly doesn't matter, the function should return a set or clearly document that the order is arbitrary and that callers should not rely on it. ## Exploration Hints ### Files to Examine: - `sympy/integrals/intpoly.py` - Contains the problematic `decompose()` function with the arbitrary ordering issue - `sympy/integrals/tests/test_intpoly.py` - Contains tests that expect a specific ordering (by increasing degree) from the `decompose()` function - `sympy/polys/polytools.py` - May contain related polynomial functionality that could inform the fix ### Key Classes/Functions: - `decompose()` in `intpoly.py` - The function directly causing the issue by returning dictionary values without preserving order - Test cases in `test_intpoly.py` - Show expected behavior where polynomial terms appear to be ordered by degree - `Poly` class - May provide insights on how to handle polynomial term ordering properly ### Areas of Interest: - The specific line where `list(poly_dict.values())` is returned when `separate=True` - How polynomial terms are organized by degree in the dictionary - How similar functions in the codebase handle ordering of mathematical components - Python version differences in dictionary ordering behavior (pre-3.7 vs 3.7+) ## Fix Hints ### High Confidence Locations: - The return statement in `decompose()` when `separate=True` is set needs modification to ensure consistent ordering ### Implementation Hints: 1. Sort dictionary values by their corresponding keys (polynomial degrees) before returning: ```python if separate: # Return sorted values based on their degree (keys) return [poly_dict[k] for k in sorted(poly_dict.keys())] return poly_dict ``` 2. Alternatively, if appropriate to the mathematical context: ```python if separate: # Sort based on some other mathematical property of the values return sorted(poly_dict.values(), key=some_comparison_function) return poly_dict ``` 3. If order truly doesn't matter, consider: ```python if separate: # Explicitly return as a set to indicate order doesn't matter return set(poly_dict.values()) return poly_dict ``` ### Alternative Hypotheses: 1. The tests might be incorrectly assuming a specific ordering - if ordering doesn't actually matter mathematically, tests should be updated to use set comparison or explicitly sort before comparison. 2. Python version differences might be exposing latent issues - code might have worked in newer Python versions (3.7+) where dictionary insertion order is preserved but fails in older environments. 3. The core changes mentioned might have altered how the polynomial dictionary is constructed, changing the insertion order in a way that now exposes the arbitrary nature of the return value.
2017-07-26T00:29:45Z
1.1
["test_decompose"]
["test_best_origin"]
ec9e3c0436fbff934fa84e22bf07f1b3ef5bfac3
sympy/sympy
sympy__sympy-14024
b17abcb09cbcee80a90f6750e0f9b53f0247656c
diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py --- a/sympy/core/numbers.py +++ b/sympy/core/numbers.py @@ -1678,11 +1678,7 @@ def _eval_power(self, expt): if (ne is S.One): return Rational(self.q, self.p) if self.is_negative: - if expt.q != 1: - return -(S.NegativeOne)**((expt.p % expt.q) / - S(expt.q))*Rational(self.q, -self.p)**ne - else: - return S.NegativeOne**ne*Rational(self.q, -self.p)**ne + return S.NegativeOne**expt*Rational(self.q, -self.p)**ne else: return Rational(self.q, self.p)**ne if expt is S.Infinity: # -oo already caught by test for negative @@ -2223,11 +2219,7 @@ def _eval_power(self, expt): # invert base and change sign on exponent ne = -expt if self.is_negative: - if expt.q != 1: - return -(S.NegativeOne)**((expt.p % expt.q) / - S(expt.q))*Rational(1, -self)**ne - else: - return (S.NegativeOne)**ne*Rational(1, -self)**ne + return S.NegativeOne**expt*Rational(1, -self)**ne else: return Rational(1, self.p)**ne # see if base is a perfect root, sqrt(4) --> 2
diff --git a/sympy/core/tests/test_numbers.py b/sympy/core/tests/test_numbers.py --- a/sympy/core/tests/test_numbers.py +++ b/sympy/core/tests/test_numbers.py @@ -1041,6 +1041,10 @@ def test_powers_Integer(): -(-1)**Rational(2, 3)*3**Rational(2, 3)/27 assert (-3) ** Rational(-2, 3) == \ -(-1)**Rational(1, 3)*3**Rational(1, 3)/3 + assert (-2) ** Rational(-10, 3) == \ + (-1)**Rational(2, 3)*2**Rational(2, 3)/16 + assert abs(Pow(-2, Rational(-10, 3)).n() - + Pow(-2, Rational(-10, 3), evaluate=False).n()) < 1e-16 # negative base and rational power with some simplification assert (-8) ** Rational(2, 5) == \ @@ -1121,6 +1125,10 @@ def test_powers_Rational(): -4*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/27 assert Rational(-3, 2)**Rational(-2, 3) == \ -(-1)**Rational(1, 3)*2**Rational(2, 3)*3**Rational(1, 3)/3 + assert Rational(-3, 2)**Rational(-10, 3) == \ + 8*(-1)**Rational(2, 3)*2**Rational(1, 3)*3**Rational(2, 3)/81 + assert abs(Pow(Rational(-2, 3), Rational(-7, 4)).n() - + Pow(Rational(-2, 3), Rational(-7, 4), evaluate=False).n()) < 1e-16 # negative integer power and negative rational base assert Rational(-2, 3) ** Rational(-2, 1) == Rational(9, 4)
# Enhanced Problem Statement: Inconsistency in Simplification and Evaluation of (-a)**x * a**(-x) ## Issue Description SymPy exhibits inconsistent behavior when simplifying and evaluating expressions of the form `(-a)**x * a**(-x)` depending on whether `a` is a symbolic variable or a concrete positive integer. The simplification step correctly transforms the expression to `(-1)**x` in both cases. However, when evaluating this expression with a fractional value for `x` (such as `-10/3`), the results differ between symbolic and concrete cases. This appears to be a branch cut issue in complex analysis. When evaluating expressions involving negative bases raised to non-integer powers, different branch cuts of the complex logarithm can be chosen, leading to different but mathematically valid results. The current implementation doesn't maintain consistent branch cut handling between symbolic simplification and numeric evaluation when concrete values are substituted. ## Reproduction Steps ```python # Case 1: Symbolic variable with assumptions a = Symbol('a', integer=True, positive=True) e = (-a)**x * a**(-x) f = simplify(e) print(e) # Output: a**(-x)*(-a)**x print(f) # Output: (-1)**x t = -S(10)/3 n1 = e.subs(x,t) n2 = f.subs(x,t) print(N(n1)) # Output: -0.5 + 0.866025403784439*I print(N(n2)) # Output: -0.5 + 0.866025403784439*I # Case 2: Concrete positive integer a = S(2) e = (-a)**x * a**(-x) f = simplify(e) print(e) # Output: (-2)**x*2**(-x) print(f) # Output: (-1)**x t = -S(10)/3 n1 = e.subs(x,t) n2 = f.subs(x,t) print(N(n1)) # Output: 0.5 - 0.866025403784439*I print(N(n2)) # Output: -0.5 + 0.866025403784439*I ``` Note that in Case 1, both the original and simplified expressions evaluate to the same complex number, while in Case 2, they evaluate to different complex numbers (which are negatives of each other). ## Expected Behavior The simplification and subsequent evaluation should yield consistent results regardless of whether `a` is symbolic or a concrete value. Either: 1. The simplification should preserve the branch cut information, ensuring that `(-a)**x * a**(-x)` and `(-1)**x` evaluate to the same value when concrete values are substituted, or 2. The simplification should add branch conditions to the result to indicate potential differences in evaluation. ## Exploration Hints ### Files to Examine: - **sympy/simplify/simplify.py** - Contains the `simplify()` function that transforms the original expression. The issue appears when simplifying expressions containing negative bases raised to symbolic powers. - **sympy/core/power.py** - Defines the `Pow` class that handles power expressions. The inconsistency involves how `(-a)**x` is evaluated differently for symbolic vs. concrete bases. - **sympy/functions/elementary/exponential.py** - Relevant for understanding how complex exponentials are handled, particularly related to branch cuts. - **sympy/core/numbers.py** - Contains implementation for numerical evaluation, particularly for complex powers with negative bases. ### Key Classes/Functions: - **simplify()** - The entry point where the transformation from `(-a)**x * a**(-x)` to `(-1)**x` occurs. - **Pow.eval() / Pow._eval_power()** - These methods handle power evaluation, particularly with negative bases. - **N()** - The numerical evaluation function that produces different results for concrete vs. symbolic expressions. - **subs()** - How substitution is handled might be contributing to the inconsistency. ### Areas of Interest: - Branch cut handling for complex powers, particularly with negative bases - How the identity `(-a)**x = (-1)**x * a**x` is implemented and under what conditions it's applied - Differences in evaluation paths between symbolic and concrete values - How assumptions on symbols (like `integer=True, positive=True`) affect simplification and evaluation ## Fix Hints ### High Confidence Locations: - **sympy/simplify/simplify.py** - The simplification logic that transforms `(-a)**x * a**(-x)` to `(-1)**x` should be examined to ensure it properly preserves branch cut information. - **sympy/core/power.py** - The handling of negative bases with symbolic exponents likely needs more careful treatment of branch cuts. ### Implementation Hints: - The simplification could be made more conservative, avoiding the transformation to `(-1)**x` when `x` might be a non-integer value. - A possible fix could involve adding branch conditions to transformations involving powers with negative bases. - Another approach would be to ensure consistent branch cut conventions between symbolic and concrete evaluation paths. - Consider using `exp_polar` for intermediate calculations to explicitly track branch information. ### Alternative Hypotheses: 1. The issue might not be in the simplification itself but in the numeric evaluation system (`N()`), which might use different branch conventions for different expression structures. 2. The problem could be in how `subs()` applies substitutions to expressions that have been simplified versus those that haven't. 3. Assumptions propagation between symbolic and concrete cases might be inconsistent, leading to different evaluation paths. 4. The issue might be a fundamental mathematical ambiguity with multivalued complex functions, requiring better documentation rather than a code fix. 5. There could be inconsistent implementation between different subsystems in SymPy handling complex powers.
More succinctly, the problem is ``` >>> (-2)**(-S(10)/3) -(-2)**(2/3)/16 ``` Pow is supposed to use the principal branch, which means (-2) has complex argument pi, which under exponentiation becomes `-10*pi/3` or equivalently `2*pi/3`. But the result of automatic simplification is different: its argument is -pi/3. The base (-1) is handled correctly, though. ``` >>> (-1)**(-S(10)/3) (-1)**(2/3) ``` Hence the inconsistency, because the simplified form of the product has (-1) in its base.
2018-01-27T05:55:11Z
1.1
["test_powers_Integer", "test_powers_Rational"]
["test_integers_cache", "test_seterr", "test_mod", "test_divmod", "test_igcd", "test_igcd_lehmer", "test_igcd2", "test_ilcm", "test_igcdex", "test_Integer_new", "test_Rational_new", "test_Number_new", "test_Rational_cmp", "test_Float", "test_float_mpf", "test_Float_RealElement", "test_Float_default_to_highprec_from_str", "test_Float_eval", "test_Float_issue_2107", "test_Float_from_tuple", "test_Infinity", "test_Infinity_2", "test_Mul_Infinity_Zero", "test_Div_By_Zero", "test_Infinity_inequations", "test_NaN", "test_special_numbers", "test_powers", "test_integer_nthroot_overflow", "test_integer_log", "test_isqrt", "test_powers_Float", "test_abs1", "test_accept_int", "test_dont_accept_str", "test_int", "test_long", "test_real_bug", "test_bug_sqrt", "test_pi_Pi", "test_no_len", "test_issue_3321", "test_issue_3692", "test_issue_3423", "test_issue_3449", "test_issue_13890", "test_Integer_factors", "test_Rational_factors", "test_issue_4107", "test_IntegerInteger", "test_Rational_gcd_lcm_cofactors", "test_Float_gcd_lcm_cofactors", "test_issue_4611", "test_conversion_to_mpmath", "test_relational", "test_Integer_as_index", "test_Rational_int", "test_zoo", "test_issue_4122", "test_GoldenRatio_expand", "test_as_content_primitive", "test_hashing_sympy_integers", "test_issue_4172", "test_Catalan_EulerGamma_prec", "test_Float_eq", "test_int_NumberSymbols", "test_issue_6640", "test_issue_6349", "test_mpf_norm", "test_latex", "test_issue_7742", "test_simplify_AlgebraicNumber", "test_Float_idempotence", "test_comp", "test_issue_9491", "test_issue_10063", "test_issue_10020", "test_invert_numbers", "test_mod_inverse", "test_golden_ratio_rewrite_as_sqrt", "test_comparisons_with_unknown_type", "test_NumberSymbol_comparison", "test_Integer_precision"]
ec9e3c0436fbff934fa84e22bf07f1b3ef5bfac3
sympy/sympy
sympy__sympy-16281
41490b75f3621408e0468b0e7b6dc409601fc6ff
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py --- a/sympy/printing/pretty/pretty.py +++ b/sympy/printing/pretty/pretty.py @@ -491,10 +491,9 @@ def _print_Product(self, expr): for lim in expr.limits: width = (func_height + 2) * 5 // 3 - 2 - sign_lines = [] - sign_lines.append(corner_chr + (horizontal_chr*width) + corner_chr) - for i in range(func_height + 1): - sign_lines.append(vertical_chr + (' '*width) + vertical_chr) + sign_lines = [horizontal_chr + corner_chr + (horizontal_chr * (width-2)) + corner_chr + horizontal_chr] + for _ in range(func_height + 1): + sign_lines.append(' ' + vertical_chr + (' ' * (width-2)) + vertical_chr + ' ') pretty_sign = stringPict('') pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines))
diff --git a/sympy/printing/pretty/tests/test_pretty.py b/sympy/printing/pretty/tests/test_pretty.py --- a/sympy/printing/pretty/tests/test_pretty.py +++ b/sympy/printing/pretty/tests/test_pretty.py @@ -2054,51 +2054,48 @@ def test_pretty_product(): unicode_str = \ u("""\ l \n\ -┬────────┬ \n\ -│ │ ⎛ 2⎞\n\ -│ │ ⎜n ⎟\n\ -│ │ f⎜──⎟\n\ -│ │ ⎝9 ⎠\n\ -│ │ \n\ +─┬──────┬─ \n\ + │ │ ⎛ 2⎞\n\ + │ │ ⎜n ⎟\n\ + │ │ f⎜──⎟\n\ + │ │ ⎝9 ⎠\n\ + │ │ \n\ 2 \n\ n = k """) ascii_str = \ """\ l \n\ __________ \n\ -| | / 2\\\n\ -| | |n |\n\ -| | f|--|\n\ -| | \\9 /\n\ -| | \n\ + | | / 2\\\n\ + | | |n |\n\ + | | f|--|\n\ + | | \\9 /\n\ + | | \n\ 2 \n\ n = k """ - assert pretty(expr) == ascii_str - assert upretty(expr) == unicode_str - expr = Product(f((n/3)**2), (n, k**2, l), (l, 1, m)) unicode_str = \ u("""\ m l \n\ -┬────────┬ ┬────────┬ \n\ -│ │ │ │ ⎛ 2⎞\n\ -│ │ │ │ ⎜n ⎟\n\ -│ │ │ │ f⎜──⎟\n\ -│ │ │ │ ⎝9 ⎠\n\ -│ │ │ │ \n\ +─┬──────┬─ ─┬──────┬─ \n\ + │ │ │ │ ⎛ 2⎞\n\ + │ │ │ │ ⎜n ⎟\n\ + │ │ │ │ f⎜──⎟\n\ + │ │ │ │ ⎝9 ⎠\n\ + │ │ │ │ \n\ l = 1 2 \n\ n = k """) ascii_str = \ """\ m l \n\ __________ __________ \n\ -| | | | / 2\\\n\ -| | | | |n |\n\ -| | | | f|--|\n\ -| | | | \\9 /\n\ -| | | | \n\ + | | | | / 2\\\n\ + | | | | |n |\n\ + | | | | f|--|\n\ + | | | | \\9 /\n\ + | | | | \n\ l = 1 2 \n\ n = k """ @@ -5514,19 +5511,19 @@ def test_issue_6359(): 2 / 2 \\ \n\ |______ | \n\ -|| | 2| \n\ -|| | x | \n\ -|| | | \n\ +| | | 2| \n\ +| | | x | \n\ +| | | | \n\ \\x = 1 / \ """ assert upretty(Product(x**2, (x, 1, 2))**2) == \ u("""\ 2 ⎛ 2 ⎞ \n\ -⎜┬────┬ ⎟ \n\ -⎜│ │ 2⎟ \n\ -⎜│ │ x ⎟ \n\ -⎜│ │ ⎟ \n\ +⎜─┬──┬─ ⎟ \n\ +⎜ │ │ 2⎟ \n\ +⎜ │ │ x ⎟ \n\ +⎜ │ │ ⎟ \n\ ⎝x = 1 ⎠ \ """)
# Product Pretty Print Improvement: Layout and Aesthetics Issues ## Issue Description The current pretty printing implementation for `Product` expressions has several aesthetic issues that detract from readability and visual elegance: 1. The product symbol (∏) is rendered with excessive width compared to other mathematical operators 2. There's an unnecessary empty line at the bottom of the rendered product, creating asymmetry and wasting vertical space 3. The overall layout isn't as visually appealing as it could be, especially when compared to similar notations like Sum (∑) These issues affect both Unicode and ASCII rendering modes, suggesting a fundamental layout problem in the pretty printing implementation for Products. ## Reproduction Steps ```python from sympy import Product, Symbol, pprint, oo n = Symbol('n') # Basic product with constant term pprint(Product(1, (n, 1, oo))) # Shows wide product symbol with empty line at bottom # Product with variable in denominator pprint(Product(1/n, (n, 1, oo))) # Shows same issues with more complex expression # Product with higher power in denominator pprint(Product(1/n**2, (n, 1, oo))) # Shows same issues with even more complex expression # Same issues appear in ASCII mode pprint(Product(1, (n, 1, oo)), use_unicode=False) ``` Internally, the pretty printer constructs the Product symbol by combining horizontal and vertical components, likely using the `stringPict` and `prettyForm` classes to assemble the representation. The issue occurs in how these components are arranged, specifically with excessive horizontal spacing and an unnecessary empty line at the bottom of the symbol. ## Expected Behavior The Product symbol should: 1. Be less wide (more proportional to the actual expression it contains) 2. Not have an empty line at the bottom 3. Potentially have an extended top bar for improved aesthetics, similar to: ``` ∞ ─┬─────┬─ │ │ 1 │ │ ── │ │ 2 │ │ n n = 1 ``` ## Exploration Hints ### Files to Examine: - `sympy/printing/pretty/pretty.py` - Contains the `PrettyPrinter` class with the `_print_Product` method that directly implements the Product pretty printing logic - `sympy/printing/pretty/pretty_symbology.py` - Defines the basic symbols and characters used in pretty printing, including the product symbol components - `sympy/printing/pretty/stringpict.py` - Implements the core rendering engine that assembles characters into multi-line string representations ### Key Classes/Functions: - `PrettyPrinter._print_Product()` - The specific method responsible for rendering Product expressions; likely contains logic for symbol construction and spacing - `stringPict` and `prettyForm` classes - Core classes that handle the layout and composition of ASCII/Unicode art elements for mathematical expressions - Symbol construction functions like `xobj()`, `vobj()`, and `hobj()` - Control the dimensions and appearance of mathematical symbols ### Areas of Interest: - Layout algorithm that determines the width of the product symbol and adds padding - Vertical spacing logic that may be adding an unnecessary empty line - Character selection for the vertical bars of the product symbol that may be making it too "fat" - Comparison with the `_print_Sum()` implementation to understand the differences in approach ## Fix Hints ### High Confidence Locations: - The `_print_Product()` method in `sympy/printing/pretty/pretty.py` is the primary location where changes are needed, as it directly implements the rendering of Product expressions ### Implementation Hints: - Reduce the width of the product symbol by modifying how the horizontal components are constructed - Remove the empty line at the bottom by adjusting the vertical padding logic - Consider offering an option to extend the top bar of the product symbol for improved aesthetics - Look at how the Sum symbol is rendered for inspiration on proportional sizing - Ensure any changes maintain compatibility with both Unicode and ASCII rendering modes ### Alternative Hypotheses: - The empty line might be intentionally added for consistency with other notation systems or to accommodate certain types of expressions - The width issue might be related to terminal font considerations rather than the code itself - The layout might be constrained by a need to maintain alignment with other mathematical notations - There might be special cases where the current rendering is actually beneficial, so testing with a variety of product expressions would be important
2019-03-16T19:37:33Z
1.4
["test_pretty_product", "test_issue_6359"]
["test_pretty_ascii_str", "test_pretty_unicode_str", "test_upretty_greek", "test_upretty_multiindex", "test_upretty_sub_super", "test_upretty_subs_missing_in_24", "test_missing_in_2X_issue_9047", "test_upretty_modifiers", "test_pretty_Cycle", "test_pretty_basic", "test_negative_fractions", "test_issue_5524", "test_pretty_ordering", "test_EulerGamma", "test_GoldenRatio", "test_pretty_relational", "test_Assignment", "test_AugmentedAssignment", "test_issue_7117", "test_pretty_rational", "test_pretty_functions", "test_pretty_sqrt", "test_pretty_sqrt_char_knob", "test_pretty_sqrt_longsymbol_no_sqrt_char", "test_pretty_KroneckerDelta", "test_pretty_lambda", "test_pretty_order", "test_pretty_derivatives", "test_pretty_integrals", "test_pretty_matrix", "test_pretty_ndim_arrays", "test_tensor_TensorProduct", "test_diffgeom_print_WedgeProduct", "test_Adjoint", "test_pretty_Trace_issue_9044", "test_MatrixExpressions", "test_pretty_dotproduct", "test_pretty_piecewise", "test_pretty_ITE", "test_pretty_seq", "test_any_object_in_sequence", "test_print_builtin_set", "test_pretty_sets", "test_pretty_SetExpr", "test_pretty_ImageSet", "test_pretty_ConditionSet", "test_pretty_ComplexRegion", "test_pretty_Union_issue_10414", "test_pretty_Intersection_issue_10414", "test_ProductSet_paranthesis", "test_ProductSet_prod_char_issue_10413", "test_pretty_sequences", "test_pretty_FourierSeries", "test_pretty_FormalPowerSeries", "test_pretty_limits", "test_pretty_ComplexRootOf", "test_pretty_RootSum", "test_GroebnerBasis", "test_pretty_Boolean", "test_pretty_Domain", "test_pretty_prec", "test_pprint", "test_pretty_class", "test_pretty_no_wrap_line", "test_settings", "test_pretty_sum", "test_units", "test_pretty_Subs", "test_gammas", "test_beta", "test_function_subclass_different_name", "test_SingularityFunction", "test_deltas", "test_hyper", "test_meijerg", "test_noncommutative", "test_pretty_special_functions", "test_pretty_geometry", "test_expint", "test_elliptic_functions", "test_RandomDomain", "test_PrettyPoly", "test_issue_6285", "test_issue_6739", "test_complicated_symbol_unchanged", "test_categories", "test_PrettyModules", "test_QuotientRing", "test_Homomorphism", "test_Tr", "test_pretty_Add", "test_issue_7179", "test_issue_7180", "test_pretty_Complement", "test_pretty_SymmetricDifference", "test_pretty_Contains", "test_issue_4335", "test_issue_6324", "test_issue_7927", "test_issue_6134", "test_issue_9877", "test_issue_13651", "test_pretty_primenu", "test_pretty_primeomega", "test_pretty_Mod", "test_issue_11801", "test_pretty_UnevaluatedExpr", "test_issue_10472", "test_MatrixElement_printing", "test_issue_12675", "test_MatrixSymbol_printing", "test_degree_printing", "test_vector_expr_pretty_printing", "test_pretty_print_tensor_expr", "test_pretty_print_tensor_partial_deriv", "test_issue_15560", "test_print_lerchphi", "test_issue_15583", "test_matrixSymbolBold", "test_center_accent"]
73b3f90093754c5ed1561bd885242330e3583004
sympy/sympy
sympy__sympy-16503
a7e6f093c98a3c4783848a19fce646e32b6e0161
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py --- a/sympy/printing/pretty/pretty.py +++ b/sympy/printing/pretty/pretty.py @@ -564,7 +564,7 @@ def adjust(s, wid=None, how='<^>'): for i in reversed(range(1, d)): lines.append('%s/%s' % (' '*i, ' '*(w - i))) lines.append("/" + "_"*(w - 1) + ',') - return d, h + more, lines, 0 + return d, h + more, lines, more else: w = w + more d = d + more @@ -619,7 +619,7 @@ def adjust(s, wid=None, how='<^>'): if first: # change F baseline so it centers on the sign prettyF.baseline -= d - (prettyF.height()//2 - - prettyF.baseline) - adjustment + prettyF.baseline) first = False # put padding to the right @@ -629,7 +629,11 @@ def adjust(s, wid=None, how='<^>'): # put the present prettyF to the right prettyF = prettyForm(*prettySign.right(prettyF)) - prettyF.baseline = max_upper + sign_height//2 + # adjust baseline of ascii mode sigma with an odd height so that it is + # exactly through the center + ascii_adjustment = ascii_mode if not adjustment else 0 + prettyF.baseline = max_upper + sign_height//2 + ascii_adjustment + prettyF.binding = prettyForm.MUL return prettyF
diff --git a/sympy/printing/pretty/tests/test_pretty.py b/sympy/printing/pretty/tests/test_pretty.py --- a/sympy/printing/pretty/tests/test_pretty.py +++ b/sympy/printing/pretty/tests/test_pretty.py @@ -4423,14 +4423,14 @@ def test_pretty_sum(): n \n\ ______ \n\ ╲ \n\ - ╲ ∞ \n\ - ╲ ⌠ \n\ - ╲ ⎮ n \n\ - ╲ ⎮ x dx\n\ - ╱ ⌡ \n\ - ╱ -∞ \n\ - ╱ k \n\ - ╱ \n\ + ╲ \n\ + ╲ ∞ \n\ + ╲ ⌠ \n\ + ╲ ⎮ n \n\ + ╱ ⎮ x dx\n\ + ╱ ⌡ \n\ + ╱ -∞ \n\ + ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ @@ -4474,14 +4474,14 @@ def test_pretty_sum(): -∞ \n\ ______ \n\ ╲ \n\ - ╲ ∞ \n\ - ╲ ⌠ \n\ - ╲ ⎮ n \n\ - ╲ ⎮ x dx\n\ - ╱ ⌡ \n\ - ╱ -∞ \n\ - ╱ k \n\ - ╱ \n\ + ╲ \n\ + ╲ ∞ \n\ + ╲ ⌠ \n\ + ╲ ⎮ n \n\ + ╱ ⎮ x dx\n\ + ╱ ⌡ \n\ + ╱ -∞ \n\ + ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ @@ -4527,14 +4527,14 @@ def test_pretty_sum(): -∞ \n\ ______ \n\ ╲ \n\ - ╲ ∞ \n\ - ╲ ⌠ \n\ - ╲ ⎮ n \n\ - ╲ ⎮ x dx\n\ - ╱ ⌡ \n\ - ╱ -∞ \n\ - ╱ k \n\ - ╱ \n\ + ╲ \n\ + ╲ ∞ \n\ + ╲ ⌠ \n\ + ╲ ⎮ n \n\ + ╱ ⎮ x dx\n\ + ╱ ⌡ \n\ + ╱ -∞ \n\ + ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ 2 2 1 x \n\ @@ -4572,14 +4572,14 @@ def test_pretty_sum(): x n \n\ ______ \n\ ╲ \n\ - ╲ ∞ \n\ - ╲ ⌠ \n\ - ╲ ⎮ n \n\ - ╲ ⎮ x dx\n\ - ╱ ⌡ \n\ - ╱ -∞ \n\ - ╱ k \n\ - ╱ \n\ + ╲ \n\ + ╲ ∞ \n\ + ╲ ⌠ \n\ + ╲ ⎮ n \n\ + ╱ ⎮ x dx\n\ + ╱ ⌡ \n\ + ╱ -∞ \n\ + ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ @@ -4602,8 +4602,8 @@ def test_pretty_sum(): ∞ \n\ ___ \n\ ╲ \n\ - ╲ x\n\ - ╱ \n\ + ╲ \n\ + ╱ x\n\ ╱ \n\ ‾‾‾ \n\ x = 0 \ @@ -4655,10 +4655,10 @@ def test_pretty_sum(): ∞ \n\ ____ \n\ ╲ \n\ - ╲ x\n\ - ╲ ─\n\ - ╱ 2\n\ - ╱ \n\ + ╲ \n\ + ╲ x\n\ + ╱ ─\n\ + ╱ 2\n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ @@ -4716,12 +4716,12 @@ def test_pretty_sum(): ∞ \n\ _____ \n\ ╲ \n\ - ╲ n\n\ - ╲ ⎛ x⎞ \n\ - ╲ ⎜ ─⎟ \n\ - ╱ ⎜ 3 2⎟ \n\ - ╱ ⎝x ⋅y ⎠ \n\ - ╱ \n\ + ╲ \n\ + ╲ n\n\ + ╲ ⎛ x⎞ \n\ + ╱ ⎜ ─⎟ \n\ + ╱ ⎜ 3 2⎟ \n\ + ╱ ⎝x ⋅y ⎠ \n\ ╱ \n\ ‾‾‾‾‾ \n\ x = 0 \ @@ -4844,14 +4844,14 @@ def test_pretty_sum(): ∞ n \n\ ______ ______ \n\ ╲ ╲ \n\ - ╲ ╲ ⎛ 1 ⎞ \n\ - ╲ ╲ ⎜1 + ─────────⎟ \n\ - ╲ ╲ ⎜ 1 ⎟ \n\ - ╲ ╲ ⎜ 1 + ─────⎟ 1 \n\ - ╱ ╱ ⎜ 1⎟ + ─────\n\ - ╱ ╱ ⎜ 1 + ─⎟ 1\n\ - ╱ ╱ ⎝ k⎠ 1 + ─\n\ - ╱ ╱ k\n\ + ╲ ╲ \n\ + ╲ ╲ ⎛ 1 ⎞ \n\ + ╲ ╲ ⎜1 + ─────────⎟ \n\ + ╲ ╲ ⎜ 1 ⎟ 1 \n\ + ╱ ╱ ⎜ 1 + ─────⎟ + ─────\n\ + ╱ ╱ ⎜ 1⎟ 1\n\ + ╱ ╱ ⎜ 1 + ─⎟ 1 + ─\n\ + ╱ ╱ ⎝ k⎠ k\n\ ╱ ╱ \n\ ‾‾‾‾‾‾ ‾‾‾‾‾‾ \n\ 1 k = 111 \n\
# Enhanced Problem Statement: Sum Pretty Print Alignment Issue ## Issue Description When a `Sum` expression is combined with another term (like a constant) in SymPy's pretty printer, the alignment of elements is incorrect. Specifically, when printing expressions like `Sum(x, (x, 1, oo)) + 3`, the summation term `x` and the external term `+ 3` are not properly aligned vertically. This suggests an issue in how the pretty printer calculates baselines and handles vertical alignment when combining expressions with different vertical structures. The issue is likely in how the `_print_Sum` method sets the baseline for the sum expression or how it's combined with other terms in the addition operation. ## Reproduction Steps ```python from sympy import Sum, Symbol, oo from sympy.printing.pretty import pprint x = Symbol('x') expr = Sum(x, (x, 1, oo)) + 3 pprint(expr) ``` Output: ``` ∞ ___ ╲ ╲ x ╱ + 3 ╱ ‾‾‾ x = 1 ``` The issue is apparent in the output where `x` and `+ 3` are misaligned. The `+ 3` appears too low compared to the summation term `x`, creating an unbalanced visual representation. ## Expected Behavior The `x` and `+ 3` should be vertically aligned at the same baseline. The pretty printer should maintain proper alignment between the summation term and any terms combined with the sum through operations like addition. Expected output should look closer to: ``` ∞ ___ ╲ ╲ x + 3 ╱ ╱ ‾‾‾ x = 1 ``` ## Exploration Hints ### Files to Examine: - **sympy/printing/pretty/pretty.py** - Contains the core pretty printing functionality and the `PrettyPrinter` class with methods like `_print_Sum` and `_print_Add` that handle the rendering of these expressions. - **sympy/printing/pretty/stringpict.py** - Implements the `stringPict` and `prettyForm` classes that are fundamental to pretty printing. These handle the representation, alignment, and composition of expressions, including baseline calculations that are critical to this issue. - **sympy/printing/pretty/tests/test_pretty.py** - Contains test cases for pretty printing. It's useful for understanding expected output formats and adding regression tests for the fix. ### Key Classes/Functions: - **PrettyPrinter._print_Sum()** - Directly responsible for formatting Sum expressions. The issue likely involves how this method calculates and sets the baseline for the sum expression, which affects alignment when combined with other terms. - **PrettyPrinter._print_Add()** - Handles addition operations in pretty printing. May need to properly respect the baselines of complex operands like Sum expressions. - **prettyForm** methods in stringpict.py - Particularly those handling horizontal composition (`__add__`, `__radd__`) and alignment (`hcenter()`), which determine how expressions are positioned relative to each other. ### Areas of Interest: - Baseline calculation logic for Sum expressions: How the pretty printer decides where the main "line" of an expression should be. - Horizontal composition mechanisms: How expressions are combined side-by-side while maintaining proper vertical alignment. - The handling of vertically complex expressions (like Sum) when they're part of binary operations like addition. ## Fix Hints ### High Confidence Locations: - **_print_Sum method in PrettyPrinter class** - The issue is likely in how this method returns the final `prettyForm` object, specifically in how it sets the baseline for the sum expression or positions the summation term. - **Horizontal composition methods in prettyForm class** - These methods handle combining expressions side-by-side, and may need to properly respect baselines for correct vertical alignment. ### Implementation Hints: - The fix likely involves adjusting how the baseline is calculated or respected when the Sum expression is rendered. - Consider whether the summation term's baseline should be the reference point for the entire Sum expression when combined with other terms. - It may be necessary to modify how the pretty printer handles the vertical positioning of the summation term (`x` in this case) relative to the overall structure of the Sum. - Examine how other vertically complex structures (like integrals or products) handle alignment in similar contexts, as they might offer insight into the correct approach. ### Alternative Hypotheses: - The issue could be in the `_print_Add` method rather than `_print_Sum`, particularly in how it handles operands with complex vertical structure. - The problem might be in how baseline information propagates through the pretty printing process, possibly getting lost when converting between internal representations. - There could be a general alignment issue in the pretty printer that's particularly visible with Sum expressions due to their vertical extent. - The issue might be specific to how infinite bounds (like `oo`) affect the vertical layout of the Sum expression.
``` >>> pprint(Sum(x**2, (x, 1, oo)) + 3) ∞ ___ ╲ ╲ 2 ╱ x + 3 ╱ ‾‾‾ x = 1 ``` This works well. So, I suppose that `x`, in the above case should be lower. Could you tell me, how I can correct it? The issue might be with the way adjustments are calculated, and this definitely works for simpler expressions: ```diff diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py index 7a3de3352..07198bea4 100644 --- a/sympy/printing/pretty/pretty.py +++ b/sympy/printing/pretty/pretty.py @@ -575,7 +575,7 @@ def adjust(s, wid=None, how='<^>'): for i in reversed(range(0, d)): lines.append('%s%s%s' % (' '*i, vsum[4], ' '*(w - i - 1))) lines.append(vsum[8]*(w)) - return d, h + 2*more, lines, more + return d, h + 2*more, lines, more // 2 f = expr.function ``` as in ```python >>> pprint(Sum(x ** n, (n, 1, oo)) + x) ∞ ___ ╲ ╲ n x + ╱ x ╱ ‾‾‾ n = 1 >>> pprint(Sum(n, (n, 1, oo)) + x) ∞ ___ ╲ ╲ x + ╱ n ╱ ‾‾‾ n = 1 ``` but this leads to test failures for more complex expressions. However, many of the tests look like they expect the misaligned sum. The ascii printer also has this issue: ``` In [1]: pprint(x + Sum(x + Integral(x**2 + x + 1, (x, 0, n)), (n, 1, oo)), use_unicode=False) oo ______ \ ` \ / n \ \ | / | \ | | | x + \ | | / 2 \ | / |x + | \x + x + 1/ dx| / | | | / | / | / \ 0 / /_____, n = 1 ```
2019-03-30T19:21:15Z
1.5
["test_pretty_sum"]
["test_pretty_ascii_str", "test_pretty_unicode_str", "test_upretty_greek", "test_upretty_multiindex", "test_upretty_sub_super", "test_upretty_subs_missing_in_24", "test_missing_in_2X_issue_9047", "test_upretty_modifiers", "test_pretty_Cycle", "test_pretty_basic", "test_negative_fractions", "test_issue_5524", "test_pretty_ordering", "test_EulerGamma", "test_GoldenRatio", "test_pretty_relational", "test_Assignment", "test_AugmentedAssignment", "test_issue_7117", "test_pretty_rational", "test_pretty_functions", "test_pretty_sqrt", "test_pretty_sqrt_char_knob", "test_pretty_sqrt_longsymbol_no_sqrt_char", "test_pretty_KroneckerDelta", "test_pretty_product", "test_pretty_lambda", "test_pretty_order", "test_pretty_derivatives", "test_pretty_integrals", "test_pretty_matrix", "test_pretty_ndim_arrays", "test_tensor_TensorProduct", "test_diffgeom_print_WedgeProduct", "test_Adjoint", "test_pretty_Trace_issue_9044", "test_MatrixExpressions", "test_pretty_dotproduct", "test_pretty_piecewise", "test_pretty_ITE", "test_pretty_seq", "test_any_object_in_sequence", "test_print_builtin_set", "test_pretty_sets", "test_pretty_SetExpr", "test_pretty_ImageSet", "test_pretty_ConditionSet", "test_pretty_ComplexRegion", "test_pretty_Union_issue_10414", "test_pretty_Intersection_issue_10414", "test_ProductSet_paranthesis", "test_ProductSet_prod_char_issue_10413", "test_pretty_sequences", "test_pretty_FourierSeries", "test_pretty_FormalPowerSeries", "test_pretty_limits", "test_pretty_ComplexRootOf", "test_pretty_RootSum", "test_GroebnerBasis", "test_pretty_Boolean", "test_pretty_Domain", "test_pretty_prec", "test_pprint", "test_pretty_class", "test_pretty_no_wrap_line", "test_settings", "test_units", "test_pretty_Subs", "test_gammas", "test_beta", "test_function_subclass_different_name", "test_SingularityFunction", "test_deltas", "test_hyper", "test_meijerg", "test_noncommutative", "test_pretty_special_functions", "test_pretty_geometry", "test_expint", "test_elliptic_functions", "test_RandomDomain", "test_PrettyPoly", "test_issue_6285", "test_issue_6359", "test_issue_6739", "test_complicated_symbol_unchanged", "test_categories", "test_PrettyModules", "test_QuotientRing", "test_Homomorphism", "test_Tr", "test_pretty_Add", "test_issue_7179", "test_issue_7180", "test_pretty_Complement", "test_pretty_SymmetricDifference", "test_pretty_Contains", "test_issue_4335", "test_issue_6324", "test_issue_7927", "test_issue_6134", "test_issue_9877", "test_issue_13651", "test_pretty_primenu", "test_pretty_primeomega", "test_pretty_Mod", "test_issue_11801", "test_pretty_UnevaluatedExpr", "test_issue_10472", "test_MatrixElement_printing", "test_issue_12675", "test_MatrixSymbol_printing", "test_degree_printing", "test_vector_expr_pretty_printing", "test_pretty_print_tensor_expr", "test_pretty_print_tensor_partial_deriv", "test_issue_15560", "test_print_lerchphi", "test_issue_15583", "test_matrixSymbolBold", "test_center_accent"]
70381f282f2d9d039da860e391fe51649df2779d
sympy/sympy
sympy__sympy-18532
74227f900b05009d4eed62e34a166228788a32ca
diff --git a/sympy/core/basic.py b/sympy/core/basic.py --- a/sympy/core/basic.py +++ b/sympy/core/basic.py @@ -503,12 +503,11 @@ def atoms(self, *types): if types: types = tuple( [t if isinstance(t, type) else type(t) for t in types]) + nodes = preorder_traversal(self) + if types: + result = {node for node in nodes if isinstance(node, types)} else: - types = (Atom,) - result = set() - for expr in preorder_traversal(self): - if isinstance(expr, types): - result.add(expr) + result = {node for node in nodes if not node.args} return result @property
diff --git a/sympy/codegen/tests/test_cnodes.py b/sympy/codegen/tests/test_cnodes.py --- a/sympy/codegen/tests/test_cnodes.py +++ b/sympy/codegen/tests/test_cnodes.py @@ -1,6 +1,6 @@ from sympy.core.symbol import symbols from sympy.printing.ccode import ccode -from sympy.codegen.ast import Declaration, Variable, float64, int64 +from sympy.codegen.ast import Declaration, Variable, float64, int64, String from sympy.codegen.cnodes import ( alignof, CommaOperator, goto, Label, PreDecrement, PostDecrement, PreIncrement, PostIncrement, sizeof, union, struct @@ -66,7 +66,7 @@ def test_sizeof(): assert ccode(sz) == 'sizeof(%s)' % typename assert sz.func(*sz.args) == sz assert not sz.is_Atom - assert all(atom == typename for atom in sz.atoms()) + assert sz.atoms() == {String('unsigned int'), String('sizeof')} def test_struct(): diff --git a/sympy/core/tests/test_basic.py b/sympy/core/tests/test_basic.py --- a/sympy/core/tests/test_basic.py +++ b/sympy/core/tests/test_basic.py @@ -137,7 +137,7 @@ def test_subs_with_unicode_symbols(): def test_atoms(): - assert b21.atoms() == set() + assert b21.atoms() == set([Basic()]) def test_free_symbols_empty():
# Enhanced Problem Statement: `expr.atoms()` Returns Wrong Leaf Nodes ## Issue Description The `expr.atoms()` method in SymPy, when called without arguments, incorrectly returns subclasses of `Atom` rather than all objects that have no `.args` (true leaf nodes). This is a semantic issue with how atomic elements are identified in the expression tree. According to the docstring of the `Atom` class, an atom is "an expression with no subexpressions," but the implementation checks class inheritance rather than this structural property. This affects the core expression traversal mechanism in SymPy, potentially causing incorrect behavior in operations that rely on proper identification of leaf nodes. ## Reproduction Steps ```python from sympy import Symbol, Basic from sympy.core.sympify import _sympify # Create a custom class that has no .args but isn't a subclass of Atom class CustomLeafNode(Basic): def __new__(cls): obj = Basic.__new__(cls) obj.args = () # Empty args, making it structurally a leaf node return obj # Create a simple expression with our custom leaf node x = Symbol('x') custom_node = CustomLeafNode() expr = x + custom_node # When calling atoms() without arguments atoms = expr.atoms() # custom_node won't be included despite having no .args, because it's not an Atom subclass ``` Internally, the `atoms()` method likely performs an `isinstance(obj, Atom)` check rather than examining if `obj.args` is empty. This creates a mismatch between the conceptual definition of an atom (no subexpressions) and the implementation (subclass of `Atom`). ## Expected Behavior The `expr.atoms()` method should return all objects that have no `.args` (true leaf nodes), regardless of whether they inherit from the `Atom` class. This aligns with the definition of an atom as "an expression with no subexpressions." The implementation should prioritize checking the structural property (`not obj.args` or `len(obj.args) == 0`) rather than class inheritance. ## Exploration Hints ### Files to Examine: - **sympy/core/basic.py** - Contains the `Basic` class with the `atoms()` method implementation. This file also defines the `Atom` class that is described as "an expression with no subexpressions," indicating that the structural definition (no args) is the correct one. - **sympy/core/expr.py** - Contains the `Expr` class which may have an overridden implementation of `atoms()` that specifically handles expression objects. ### Key Classes/Functions: - **Basic.atoms()** - The fundamental implementation that traverses the expression tree and collects atoms. This is likely where the bug exists, as it probably checks for `isinstance(obj, Atom)` instead of checking if `obj.args` is empty. - **Atom class** - Defines the base class for atomic elements. Its docstring states it's "an expression with no subexpressions," and its `_sorted_args` property raises an `AttributeError`, confirming atoms should have no args. - **Expr.atoms()** - May override the basic implementation with expression-specific logic that contains the same issue. ### Areas of Interest: - The filtering logic in the `atoms()` method that determines what objects to include in the returned set - Any performance optimizations in the traversal algorithm that might be relying on class-based checks - The recursive traversal logic that collects atoms from subexpressions ## Fix Hints ### High Confidence Locations: - The `atoms()` method in the `Basic` class in `sympy/core/basic.py` is the most likely place for the fix. The method should be modified to check for empty `.args` rather than class membership. ### Implementation Hints: - Change the condition from `isinstance(obj, Atom)` or similar to check for `not obj.args` or `len(obj.args) == 0`. - This change needs careful performance testing, as mentioned in the original bug report. Checking properties can be more expensive than class-based checks. - Consider adding a test case with a custom class that has empty `.args` but isn't a subclass of `Atom` to verify the fix works correctly. - The fix should preserve special-case handling for specific types if they exist in the current implementation. ### Alternative Hypotheses: - There might be objects with empty `.args` that shouldn't be considered atoms for certain operations, requiring more complex logic than a simple property check. - Performance degradation might be significant if the tree traversal is a common operation in computational bottlenecks, requiring additional optimization strategies. - There could be backward compatibility issues if other code relies on the current behavior, suggesting a need for a transition period or deprecation warning. - The issue might be part of a larger conceptual inconsistency in how SymPy defines and handles atomic expressions throughout the codebase, requiring a more comprehensive review.
The docstring should also be updated. Hi, can i work on this? Sure. Did you read https://github.com/sympy/sympy/wiki/Introduction-to-contributing? How should I remove .args? Should I try to remove ._args from object instance or add a new attribute to class Atom(), is_leave. Which when assigned as false, will raise attribute error on .args. Or if creating a new object, what attributes should it have? I think you're misunderstanding the issue. The issue is not to remove .args. Indeed, every SymPy object should have .args in order to be valid. The issue is that the `atoms()` method currently uses `x.is_Atom` to check for "atomic" expressions (expressions with no subexpressions), but it really should be checking `not x.args`. It should be a simple one-line fix to the `atoms` function definition, but a new test should be added, and the full test suite run to make sure it doesn't break anything (`./bin/test` from the sympy directory). Okay. But, Basic() also return .args to be null. So will not that also appear in the result of .atoms()? Yes, that's an example of an object with no args but that isn't a subclass of Atom. `atoms` should return that, because it's a leaf in the expression tree. Okay, but if I am understanding you correct, won't this test fail? https://github.com/sympy/sympy/blob/master/sympy/core/tests/test_basic.py#L73 Yes, it would need to be changed. This is a slight redefinition of what `atoms` means (although hopefully not enough of a breaking behavior to require deprecation). Can you look over it once and look if it is okay? https://github.com/sympy/sympy/pull/10246 @asmeurer When I ran the full suite of tests, sympy/vector/tests/test_field_functions.py failed on all the tests. ``` Original- if not (types or expr.args): result.add(expr) Case 1- if not types: if isinstance(expr, Atom): result.add(expr) Case 2- if not (types or expr.args): if isinstance(expr, Atom): result.add(expr) ``` I saw that fails even on the second case. Then I saw the items that case1 had but case2 did not. Which were all either `C.z <class 'sympy.vector.scalar.BaseScalar'>` or `C.k <class 'sympy.vector.vector.BaseVector'>`. Elements of the class sympy.vector.scaler.BaseScalar or class sympy.vector.vector.BaseVector were earlier considered but not now, as they were Atom but had arguments. So what should we do? I want to fix this if no one is working on it. I am unable to figure out why 'Atom' has been assigned to 'types' . We can add the result while checking for the types and if there are no types then we can simply add x.args to the result. That way it will return null and we will not be having subclasses of Atom. ping @asmeurer @darkcoderrises I have some fixes at https://github.com/sympy/sympy/pull/10084 which might make your issues go away. Once that is merged you should try merging your branch into master and see if it fixes the problems. ok I merged the pull requests, and now the tests are passing. What should be my next step. https://github.com/sympy/sympy/pull/10246 I am working on this issue
2020-02-01T17:26:30Z
1.6
["test_sizeof", "test_atoms"]
["test_alignof", "test_CommaOperator", "test_goto_Label", "test_PreDecrement", "test_PostDecrement", "test_PreIncrement", "test_PostIncrement", "test_struct", "test__aresame", "test_structure", "test_equality", "test_matches_basic", "test_has", "test_subs", "test_subs_with_unicode_symbols", "test_free_symbols_empty", "test_doit", "test_S", "test_xreplace", "test_preorder_traversal", "test_sorted_args", "test_call", "test_rewrite", "test_literal_evalf_is_number_is_zero_is_comparable", "test_as_Basic", "test_atomic", "test_as_dummy", "test_canonical_variables"]
28b41c73c12b70d6ad9f6e45109a80649c4456da
sympy/sympy
sympy__sympy-19487
25fbcce5b1a4c7e3956e6062930f4a44ce95a632
diff --git a/sympy/functions/elementary/complexes.py b/sympy/functions/elementary/complexes.py --- a/sympy/functions/elementary/complexes.py +++ b/sympy/functions/elementary/complexes.py @@ -394,6 +394,9 @@ def _eval_rewrite_as_Heaviside(self, arg, **kwargs): if arg.is_extended_real: return Heaviside(arg, H0=S(1)/2) * 2 - 1 + def _eval_rewrite_as_Abs(self, arg, **kwargs): + return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True)) + def _eval_simplify(self, **kwargs): return self.func(self.args[0].factor()) # XXX include doit?
diff --git a/sympy/core/tests/test_subs.py b/sympy/core/tests/test_subs.py --- a/sympy/core/tests/test_subs.py +++ b/sympy/core/tests/test_subs.py @@ -855,3 +855,10 @@ def test_issue_17823(): def test_issue_19326(): x, y = [i(t) for i in map(Function, 'xy')] assert (x*y).subs({x: 1 + x, y: x}) == (1 + x)*x + +def test_issue_19558(): + e = (7*x*cos(x) - 12*log(x)**3)*(-log(x)**4 + 2*sin(x) + 1)**2/ \ + (2*(x*cos(x) - 2*log(x)**3)*(3*log(x)**4 - 7*sin(x) + 3)**2) + + assert e.subs(x, oo) == AccumBounds(-oo, oo) + assert (sin(x) + cos(x)).subs(x, oo) == AccumBounds(-2, 2) diff --git a/sympy/functions/elementary/tests/test_complexes.py b/sympy/functions/elementary/tests/test_complexes.py --- a/sympy/functions/elementary/tests/test_complexes.py +++ b/sympy/functions/elementary/tests/test_complexes.py @@ -4,7 +4,7 @@ pi, Rational, re, S, sign, sin, sqrt, Symbol, symbols, transpose, zoo, exp_polar, Piecewise, Interval, comp, Integral, Matrix, ImmutableMatrix, SparseMatrix, ImmutableSparseMatrix, MatrixSymbol, - FunctionMatrix, Lambda, Derivative) + FunctionMatrix, Lambda, Derivative, Eq) from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import XFAIL, raises @@ -296,11 +296,14 @@ def test_sign(): assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None x, y = Symbol('x', real=True), Symbol('y') + f = Function('f') assert sign(x).rewrite(Piecewise) == \ Piecewise((1, x > 0), (-1, x < 0), (0, True)) assert sign(y).rewrite(Piecewise) == sign(y) assert sign(x).rewrite(Heaviside) == 2*Heaviside(x, H0=S(1)/2) - 1 assert sign(y).rewrite(Heaviside) == sign(y) + assert sign(y).rewrite(Abs) == Piecewise((0, Eq(y, 0)), (y/Abs(y), True)) + assert sign(f(y)).rewrite(Abs) == Piecewise((0, Eq(f(y), 0)), (f(y)/Abs(f(y)), True)) # evaluate what can be evaluated assert sign(exp_polar(I*pi)*pi) is S.NegativeOne
# Enhanced Problem Statement: Implementing Rewrite of sign as abs in SymPy ## Issue Description SymPy lacks a mechanism to rewrite the `sign` function in terms of the `Abs` function despite their mathematical relationship. According to the mathematical definition, `sign(z) = z / Abs(z)` for all complex non-zero values. Currently, users cannot use the `.rewrite(Abs)` method on the `sign` function to express it in terms of `Abs`. There's an inconsistency between the mathematical definition and the implementation: `sign(0)` returns `0`, but `0/Abs(0)` produces `nan`. This discrepancy creates a challenge for implementing the rewrite functionality, as it requires resolving how to handle the zero case in the rewrite mechanism. ## Reproduction Steps ```python >>> from sympy import sign, Symbol, Abs >>> x = Symbol('x') >>> sign(x).rewrite(Abs) # Currently fails or doesn't perform the expected rewrite >>> sign(0) 0 # Current behavior >>> 0 / Abs(0) nan # Mathematical definition would give this ``` This failure occurs because there is no `_eval_rewrite_as_Abs` method in the `sign` class within `sympy/functions/elementary/complexes.py`. SymPy's rewrite system looks for specialized methods following the `_eval_rewrite_as_X` pattern to perform rewrites. ## Expected Behavior The `sign` function should be rewritable in terms of `Abs`, with special handling for the zero case: ```python >>> sign(x).rewrite(Abs) x/Abs(x) # For non-zero symbolic expressions ``` The solution must address one of two options: 1. Keep `sign(0) = 0` as currently implemented, and make the rewrite method handle zero as a special case 2. Change the behavior of `sign(0)` to return `nan` to align with the mathematical definition `z/Abs(z)` ## Exploration Hints ### Files to Examine: - `sympy/functions/elementary/complexes.py` - Contains the implementation of both `sign` and `Abs` classes. This is the primary file that needs modification to implement the rewrite functionality. ### Key Classes/Functions: - `sign` class - Needs a new `_eval_rewrite_as_Abs` method to implement the requested functionality. Currently handles `sign(0)` as a special case, returning `0` instead of following the mathematical definition. - `Abs` class - Provides the absolute value functionality required for the rewrite. Understanding its implementation details will help ensure the rewrite works correctly for all types of arguments. - `_eval_rewrite` mechanism - The general pattern in SymPy where specialized `_eval_rewrite_as_X` methods are called to convert expressions between different forms. ### Areas of Interest: - How zero values are handled in the current `sign` implementation - The pattern used in other SymPy functions for implementing rewrite methods - The relationship between complex arguments and the `sign` function ## Fix Hints ### High Confidence Locations: - `sign` class in `sympy/functions/elementary/complexes.py` - A new `_eval_rewrite_as_Abs` method should be added here to implement the requested functionality. ### Implementation Hints: 1. **Option 1**: Keep the current behavior of `sign(0) = 0` and implement a special case in the rewrite: ```python def _eval_rewrite_as_Abs(self, arg, **hints): from sympy import Piecewise return Piecewise((arg/Abs(arg), arg != 0), (0, True)) ``` 2. **Option 2**: If changing the behavior of `sign(0)` is acceptable, modify `sign` to return `nan` for zero arguments to be consistent with the mathematical definition, then implement the rewrite simply as: ```python def _eval_rewrite_as_Abs(self, arg, **hints): return arg/Abs(arg) ``` 3. **Option 3**: Implement the rewrite directly but add a warning when the argument could be zero. ### Alternative Hypotheses: 1. The inconsistency between `sign(0) = 0` and the mathematical definition might be intentional for practical reasons, suggesting that option 1 is more aligned with SymPy's design philosophy. 2. This issue might be part of a broader pattern of handling undefined mathematical operations in SymPy, and the solution should be consistent with similar cases in the library. 3. There might be performance implications of different approaches, especially if adding conditional checks for zero values. 4. The rewrite functionality might interact with SymPy's assumptions system, particularly when handling expressions that might be zero under certain assumptions.
Getting nan for `sign(0)` would be pretty [non-intuitive](https://en.wikipedia.org/wiki/Sign_function) for any mathematical programmer given it's non-derivative definition. If a rewrite request cannot be fulfilled under all conditions and the request was not for Piecewise, I think the rewrite should return None. Actually I think it's fine if the rewrite doesn't always work. At least something like this could rewrite: ```julia In [2]: sign(1+I).rewrite(Abs) Out[2]: sign(1 + ⅈ) ``` You can use piecewise like ``` Piecewise( (0, Eq(x, 0)), (x / Abs(x), Ne(x, 0)) ) ``` Originally this question comes from SO: https://stackoverflow.com/questions/61676438/integrating-and-deriving-absolute-functions-sympy/61681347#61681347 The original question was about `diff(Abs(x))`: ``` In [2]: x = Symbol('x', real=True) In [3]: Abs(x).diff(x) Out[3]: sign(x) ``` Maybe the result from `diff` should be a `Piecewise` or at least an `ExprCondPair` guarding against `x=0`. The problem is that real-valued functions like abs, re, im, arg,... are not holomorphic and have no complex derivative. See also https://github.com/sympy/sympy/issues/8502. @jksuom could we add conditions in the `Derivative` class of the functions module which would check if the expression is an instance of a non-holomorphic function, in such a case it could raise an error or in the case of `Abs` simply check the domain. I believe all the classes in `sympy/functions/elementary/complexes.py` could be checked. Would it be possible to add an `_eval_derivative` method raising an error to those functions? When would it raise? If the function is non-holomorphic, there is no derivative to be returned. There is a reasonable derivative of `Abs` when defined over the reals though e.g.: ```julia In [1]: x = Symbol('x', real=True) In [2]: Abs(x).diff(x) Out[2]: sign(x) ``` Maybe there should be two functions, one defined on reals and the other on complexes. > Would it be possible to add an `_eval_derivative` method raising an error to those functions? In the `Derivative` class in `sympy.function`? > When would it raise? As suggested, if the function is non-holomorphic or in the case of `Abs()` it could be a check on the domain of the argument. > Maybe there should be two functions, one defined on reals and the other on complexes. I am not sure if there are any non-holomorphic functions on Real numbers. In my opinion only the `Abs()` function would fall in this case. Hence I think this could be done using one function only. ``` def _eval_derivative(self, expr): if isinstance(expr,[re, im, sign, arg, conjugate]): raise TypeError("Derivative not possible for Non-Holomorphic functions") if isinstance(expr,Abs): if Abs.arg[0].free_symbols.is_complex: raises TypeError("There is a complex argument which makes Abs non-holomorphic") ``` This is something I was thinking but I am not sure about it as `Derivative` class already has a method with the same name. I also think that appropriate changes also need to be made in the `fdiff()` method of the `Abs` class. @jksuom I wanted to know if there are more non-holomorphic functions in sympy/functions/elementary/complexes.py to which an error can be raised. Those functions in complexes.py have a `_eval_derivative` method. Maybe that would be the proper place for raising an error if that is desired. Are there any other examples of functions that raise when differentiated? I just tried ```julia In [83]: n = Symbol('n', integer=True, positive=True) In [84]: totient(n).diff(n) Out[84]: d ──(totient(n)) dn ``` @oscarbenjamin I am not sure if this is a situation when it should raise, for example: if `n` here is a prime number the derivative wrt `n` would hence be `1` . Although in sympy ``` >>> x = Symbol('x', real=True, prime=True) >>> totient(x).evalf() ϕ(x) ``` is the output and not `x-1`.Maybe this kind of functionality can be added. @jksuom I think your way is correct and wanted to ask if the error to be raised is appropriately `TypeError`? I don't think that the totient function should be differentiable. I was just trying to think of functions where it might be an error to differentiate them. I think it's better to leave the derivative of Abs unevaluated. You might have something like `Abs(f(x))` where `f` can be substituted for something reasonable later. @dhruvmendiratta6 Yes, I think that `TypeError` would be the appropriate choice. Note, however, that raising errors would probably break some tests. It may be desirable to add some try-except blocks to handle those properly. What about something like this: ```julia In [21]: x = Symbol('x', real=True) In [22]: f = Function('f') In [23]: e = Derivative(Abs(f(x)), x) In [24]: e Out[24]: d ──(│f(x)│) dx In [25]: e.subs(f, cosh) Out[25]: d ──(cosh(x)) dx In [26]: e.subs(f, cosh).doit() Out[26]: sinh(x) ``` @jksuom @oscarbenjamin Any suggestion on how this can be done? I think changes need to be made here https://github.com/sympy/sympy/blob/7c11a00d4ace555e8be084d69c4da4e6f4975f64/sympy/functions/elementary/complexes.py#L605-L608 to leave the derivative of `Abs` unevaluated. I tried changing this to ``` def _eval_derivative(self, x): if self.args[0].is_extended_real or self.args[0].is_imaginary: return Derivative(self.args[0], x, evaluate=True) \ * Derivative(self, x, evaluate=False) ``` which gives ``` >>> x = Symbol('x', real = True) >>> Abs(x**3).diff(x) x**2*Derivative(Abs(x), x) + 2*x*Abs(x) ``` But then I can't figure out how to evaluate when the need arises.The above result,which I think is wrong, occurs even when no changes are made. I think rewrite in general can't avoid having situations where things are only defined correctly in the limit, unless we return a Piecewise. For example, `sinc(x).rewrite(sin)`. ```py >>> pprint(sinc(x).rewrite(sin)) ⎧sin(x) ⎪────── for x ≠ 0 ⎨ x ⎪ ⎩ 1 otherwise ``` I made `_eval_rewrite_as_Abs()` for the `sign` class which gives the following: ``` >>> sign(x).rewrite(Abs) Piecewise((0, Eq(x, 0)), (x/Abs(x), True)) ``` Although as discussed earlier raising an error in `_eval_derivative()` causes some tests to break : ``` File "c:\users\mendiratta\sympy\sympy\functions\elementary\tests\test_complexes.py", line 414, in test_Abs assert Abs(x).diff(x) == -sign(x) File "c:\users\mendiratta\sympy\sympy\functions\elementary\tests\test_complexes.py", line 833, in test_derivatives_issue_4757 assert Abs(f(x)).diff(x).subs(f(x), 1 + I*x).doit() == x/sqrt(1 + x**2) File "c:\users\mendiratta\sympy\sympy\functions\elementary\tests\test_complexes.py", line 969, in test_issue_15893 assert eq.doit() == sign(f(x)) ``` The first two are understood but in the third one both `f` and `x` are real and still are caught by the newly raised error which doesn't make sense as I raised a `TypeError` only if the argument is not real.
2020-06-04T09:25:34Z
1.7
["test_sign"]
["test_subs", "test_subs_Matrix", "test_subs_AccumBounds", "test_trigonometric", "test_powers", "test_logexppow", "test_bug", "test_subbug1", "test_subbug2", "test_dict_set", "test_dict_ambigous", "test_deriv_sub_bug3", "test_equality_subs1", "test_equality_subs2", "test_issue_3742", "test_subs_dict1", "test_mul", "test_subs_simple", "test_subs_constants", "test_subs_commutative", "test_subs_noncommutative", "test_subs_basic_funcs", "test_subs_wild", "test_subs_mixed", "test_division", "test_add", "test_subs_issue_4009", "test_functions_subs", "test_derivative_subs", "test_derivative_subs2", "test_derivative_subs3", "test_issue_5284", "test_subs_iter", "test_subs_dict", "test_no_arith_subs_on_floats", "test_issue_5651", "test_issue_6075", "test_issue_6079", "test_issue_4680", "test_issue_6158", "test_Function_subs", "test_simultaneous_subs", "test_issue_6419_6421", "test_issue_6559", "test_issue_5261", "test_issue_6923", "test_2arg_hack", "test_noncommutative_subs", "test_issue_2877", "test_issue_5910", "test_issue_5217", "test_issue_10829", "test_pow_eval_subs_no_cache", "test_RootOf_issue_10092", "test_issue_8886", "test_issue_12657", "test_recurse_Application_args", "test_Subs_subs", "test_issue_13333", "test_issue_15234", "test_issue_6976", "test_issue_11746", "test_issue_17823", "test_issue_19326", "test_re", "test_im", "test_as_real_imag", "test_Abs", "test_Abs_rewrite", "test_Abs_real", "test_Abs_properties", "test_abs", "test_arg", "test_arg_rewrite", "test_adjoint", "test_conjugate", "test_conjugate_transpose", "test_transpose", "test_polarify", "test_unpolarify", "test_issue_4035", "test_issue_3206", "test_issue_4754_derivative_conjugate", "test_derivatives_issue_4757", "test_issue_11413", "test_periodic_argument", "test_principal_branch", "test_issue_14216", "test_issue_14238", "test_zero_assumptions"]
cffd4e0f86fefd4802349a9f9b19ed70934ea354
sympy/sympy
sympy__sympy-20639
eb926a1d0c1158bf43f01eaf673dc84416b5ebb1
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py --- a/sympy/printing/pretty/pretty.py +++ b/sympy/printing/pretty/pretty.py @@ -1902,12 +1902,12 @@ def _print_Mul(self, product): return prettyForm.__mul__(*a)/prettyForm.__mul__(*b) # A helper function for _print_Pow to print x**(1/n) - def _print_nth_root(self, base, expt): + def _print_nth_root(self, base, root): bpretty = self._print(base) # In very simple cases, use a single-char root sign if (self._settings['use_unicode_sqrt_char'] and self._use_unicode - and expt is S.Half and bpretty.height() == 1 + and root == 2 and bpretty.height() == 1 and (bpretty.width() == 1 or (base.is_Integer and base.is_nonnegative))): return prettyForm(*bpretty.left('\N{SQUARE ROOT}')) @@ -1915,14 +1915,13 @@ def _print_nth_root(self, base, expt): # Construct root sign, start with the \/ shape _zZ = xobj('/', 1) rootsign = xobj('\\', 1) + _zZ - # Make exponent number to put above it - if isinstance(expt, Rational): - exp = str(expt.q) - if exp == '2': - exp = '' - else: - exp = str(expt.args[0]) - exp = exp.ljust(2) + # Constructing the number to put on root + rpretty = self._print(root) + # roots look bad if they are not a single line + if rpretty.height() != 1: + return self._print(base)**self._print(1/root) + # If power is half, no number should appear on top of root sign + exp = '' if root == 2 else str(rpretty).ljust(2) if len(exp) > 2: rootsign = ' '*(len(exp) - 2) + rootsign # Stack the exponent @@ -1954,8 +1953,9 @@ def _print_Pow(self, power): if e is S.NegativeOne: return prettyForm("1")/self._print(b) n, d = fraction(e) - if n is S.One and d.is_Atom and not e.is_Integer and self._settings['root_notation']: - return self._print_nth_root(b, e) + if n is S.One and d.is_Atom and not e.is_Integer and (e.is_Rational or d.is_Symbol) \ + and self._settings['root_notation']: + return self._print_nth_root(b, d) if e.is_Rational and e < 0: return prettyForm("1")/self._print(Pow(b, -e, evaluate=False))
diff --git a/sympy/printing/pretty/tests/test_pretty.py b/sympy/printing/pretty/tests/test_pretty.py --- a/sympy/printing/pretty/tests/test_pretty.py +++ b/sympy/printing/pretty/tests/test_pretty.py @@ -5942,7 +5942,11 @@ def test_PrettyPoly(): def test_issue_6285(): assert pretty(Pow(2, -5, evaluate=False)) == '1 \n--\n 5\n2 ' - assert pretty(Pow(x, (1/pi))) == 'pi___\n\\/ x ' + assert pretty(Pow(x, (1/pi))) == \ + ' 1 \n'\ + ' --\n'\ + ' pi\n'\ + 'x ' def test_issue_6359(): @@ -7205,6 +7209,51 @@ def test_is_combining(): [False, True, False, False] +def test_issue_17616(): + assert pretty(pi**(1/exp(1))) == \ + ' / -1\\\n'\ + ' \e /\n'\ + 'pi ' + + assert upretty(pi**(1/exp(1))) == \ + ' ⎛ -1⎞\n'\ + ' ⎝ℯ ⎠\n'\ + 'π ' + + assert pretty(pi**(1/pi)) == \ + ' 1 \n'\ + ' --\n'\ + ' pi\n'\ + 'pi ' + + assert upretty(pi**(1/pi)) == \ + ' 1\n'\ + ' ─\n'\ + ' π\n'\ + 'π ' + + assert pretty(pi**(1/EulerGamma)) == \ + ' 1 \n'\ + ' ----------\n'\ + ' EulerGamma\n'\ + 'pi ' + + assert upretty(pi**(1/EulerGamma)) == \ + ' 1\n'\ + ' ─\n'\ + ' γ\n'\ + 'π ' + + z = Symbol("x_17") + assert upretty(7**(1/z)) == \ + 'x₁₇___\n'\ + ' ╲╱ 7 ' + + assert pretty(7**(1/z)) == \ + 'x_17___\n'\ + ' \\/ 7 ' + + def test_issue_17857(): assert pretty(Range(-oo, oo)) == '{..., -1, 0, 1, ...}' assert pretty(Range(oo, -oo, -1)) == '{..., 1, 0, -1, ...}'
inaccurate rendering of pi**(1/E) This claims to be version 1.5.dev; I just merged from the project master, so I hope this is current. I didn't notice this bug among others in printing.pretty. ``` In [52]: pi**(1/E) Out[52]: -1___ ╲╱ π ``` LaTeX and str not fooled: ``` In [53]: print(latex(pi**(1/E))) \pi^{e^{-1}} In [54]: str(pi**(1/E)) Out[54]: 'pi**exp(-1)' ```
I can confirm this bug on master. Looks like it's been there a while https://github.com/sympy/sympy/blob/2d700c4b3c0871a26741456787b0555eed9d5546/sympy/printing/pretty/pretty.py#L1814 `1/E` is `exp(-1)` which has totally different arg structure than something like `1/pi`: ``` >>> (1/E).args (-1,) >>> (1/pi).args (pi, -1) ``` @ethankward nice! Also, the use of `str` there isn't correct: ``` >>> pprint(7**(1/(pi))) pi___ ╲╱ 7 >>> pprint(pi**(1/(pi))) pi___ ╲╱ π >>> pprint(pi**(1/(EulerGamma))) EulerGamma___ ╲╱ π ``` (`pi` and `EulerGamma` were not pretty printed) I guess str is used because it's hard to put 2-D stuff in the corner of the radical like that. But I think it would be better to recursively call the pretty printer, and if it is multiline, or maybe even if it is a more complicated expression than just a single number or symbol name, then print it without the radical like ``` 1 ─ e π ``` or ``` ⎛ -1⎞ ⎝e ⎠ π
2020-12-21T07:42:53Z
1.8
["test_issue_6285", "test_issue_17616"]
["test_pretty_ascii_str", "test_pretty_unicode_str", "test_upretty_greek", "test_upretty_multiindex", "test_upretty_sub_super", "test_upretty_subs_missing_in_24", "test_missing_in_2X_issue_9047", "test_upretty_modifiers", "test_pretty_Cycle", "test_pretty_Permutation", "test_pretty_basic", "test_negative_fractions", "test_issue_5524", "test_pretty_ordering", "test_EulerGamma", "test_GoldenRatio", "test_pretty_relational", "test_Assignment", "test_AugmentedAssignment", "test_pretty_rational", "test_pretty_functions", "test_pretty_sqrt", "test_pretty_sqrt_char_knob", "test_pretty_sqrt_longsymbol_no_sqrt_char", "test_pretty_KroneckerDelta", "test_pretty_product", "test_pretty_Lambda", "test_pretty_TransferFunction", "test_pretty_Series", "test_pretty_Parallel", "test_pretty_Feedback", "test_pretty_order", "test_pretty_derivatives", "test_pretty_integrals", "test_pretty_matrix", "test_pretty_ndim_arrays", "test_tensor_TensorProduct", "test_diffgeom_print_WedgeProduct", "test_Adjoint", "test_pretty_Trace_issue_9044", "test_MatrixSlice", "test_MatrixExpressions", "test_pretty_dotproduct", "test_pretty_piecewise", "test_pretty_ITE", "test_pretty_seq", "test_any_object_in_sequence", "test_print_builtin_set", "test_pretty_sets", "test_pretty_SetExpr", "test_pretty_ImageSet", "test_pretty_ConditionSet", "test_pretty_ComplexRegion", "test_pretty_Union_issue_10414", "test_pretty_Intersection_issue_10414", "test_ProductSet_exponent", "test_ProductSet_parenthesis", "test_ProductSet_prod_char_issue_10413", "test_pretty_sequences", "test_pretty_FourierSeries", "test_pretty_FormalPowerSeries", "test_pretty_limits", "test_pretty_ComplexRootOf", "test_pretty_RootSum", "test_GroebnerBasis", "test_pretty_UniversalSet", "test_pretty_Boolean", "test_pretty_Domain", "test_pretty_prec", "test_pprint", "test_pretty_class", "test_pretty_no_wrap_line", "test_settings", "test_pretty_sum", "test_units", "test_pretty_Subs", "test_gammas", "test_beta", "test_function_subclass_different_name", "test_SingularityFunction", "test_deltas", "test_hyper", "test_meijerg", "test_noncommutative", "test_pretty_special_functions", "test_pretty_geometry", "test_expint", "test_elliptic_functions", "test_RandomDomain", "test_PrettyPoly", "test_issue_6359", "test_issue_6739", "test_complicated_symbol_unchanged", "test_categories", "test_PrettyModules", "test_QuotientRing", "test_Homomorphism", "test_Tr", "test_pretty_Add", "test_issue_7179", "test_issue_7180", "test_pretty_Complement", "test_pretty_SymmetricDifference", "test_pretty_Contains", "test_issue_8292", "test_issue_4335", "test_issue_8344", "test_issue_6324", "test_issue_7927", "test_issue_6134", "test_issue_9877", "test_issue_13651", "test_pretty_primenu", "test_pretty_primeomega", "test_pretty_Mod", "test_issue_11801", "test_pretty_UnevaluatedExpr", "test_issue_10472", "test_MatrixElement_printing", "test_issue_12675", "test_MatrixSymbol_printing", "test_degree_printing", "test_vector_expr_pretty_printing", "test_pretty_print_tensor_expr", "test_pretty_print_tensor_partial_deriv", "test_issue_15560", "test_print_lerchphi", "test_issue_15583", "test_matrixSymbolBold", "test_center_accent", "test_imaginary_unit", "test_str_special_matrices", "test_pretty_misc_functions", "test_hadamard_power", "test_issue_17258", "test_is_combining", "test_issue_17857", "test_issue_18272", "test_Str"]
3ac1464b8840d5f8b618a654f9fbf09c452fe969
sympy/sympy
sympy__sympy-22005
2c83657ff1c62fc2761b639469fdac7f7561a72a
diff --git a/sympy/solvers/polysys.py b/sympy/solvers/polysys.py --- a/sympy/solvers/polysys.py +++ b/sympy/solvers/polysys.py @@ -240,6 +240,12 @@ def _solve_reduced_system(system, gens, entry=False): univariate = list(filter(_is_univariate, basis)) + if len(basis) < len(gens): + raise NotImplementedError(filldedent(''' + only zero-dimensional systems supported + (finite number of solutions) + ''')) + if len(univariate) == 1: f = univariate.pop() else:
diff --git a/sympy/solvers/tests/test_polysys.py b/sympy/solvers/tests/test_polysys.py --- a/sympy/solvers/tests/test_polysys.py +++ b/sympy/solvers/tests/test_polysys.py @@ -49,6 +49,11 @@ def test_solve_poly_system(): [z, -2*x*y**2 + x + y**2*z, y**2*(-z - 4) + 2])) raises(PolynomialError, lambda: solve_poly_system([1/x], x)) + raises(NotImplementedError, lambda: solve_poly_system( + [x-1,], (x, y))) + raises(NotImplementedError, lambda: solve_poly_system( + [y-1,], (x, y))) + def test_solve_biquadratic(): x0, y0, x1, y1, r = symbols('x0 y0 x1 y1 r')
# Enhanced Problem Statement: Inconsistent Handling of Underdetermined Polynomial Systems ## Issue Description The `solve_poly_system` function fails to correctly identify and handle polynomial systems with infinite solutions (underdetermined systems). Specifically, when solving a system where one variable is constrained but others remain free, the function inconsistently handles these cases depending on which variable is constrained. For example, `solve_poly_system((x - 1,), x, y)` correctly raises a `NotImplementedError` indicating that only zero-dimensional systems are supported, but `solve_poly_system((y - 1,), x, y)` incorrectly returns `[(1,)]` without acknowledging that this is an underdetermined system with infinite solutions (where `x` can take any value). This inconsistency stems from a logic error in `_solve_reduced_system()` where the function only checks if there's a single univariate polynomial without verifying that the number of equations matches the number of variables. For underdetermined systems, the solver should consistently raise the appropriate exception rather than producing incomplete or incorrect results. ## Reproduction Steps ```python from sympy import symbols from sympy.solvers.polysys import solve_poly_system x, y = symbols('x y') # This correctly raises NotImplementedError solve_poly_system((x - 1,), x, y) # NotImplementedError: only zero-dimensional systems supported (finite number of solutions) # This incorrectly returns [(1,)] instead of raising the same error solve_poly_system((y - 1,), x, y) # Returns: [(1,)] ``` Internally, what happens: 1. When processing `(y - 1,)` with variables `x, y`, the function finds a univariate polynomial in `y` 2. It computes solutions for this polynomial, getting `y = 1` 3. It fails to recognize that `x` remains unconstrained, leading to infinite solutions 4. It returns a solution tuple that doesn't properly represent the infinite solution space ## Expected Behavior Both cases should consistently raise a `NotImplementedError` with a message indicating that only zero-dimensional systems (with finite solutions) are supported. Underdetermined systems with infinite solutions should be identified regardless of which variable is constrained and which remains free. ## Exploration Hints ### Files to Examine: - **sympy/solvers/polysys.py** - Contains the core implementation of polynomial system solving, including the faulty condition in `_solve_reduced_system()` that incorrectly handles univariate polynomials in multi-variable contexts. - **sympy/solvers/tests/test_polysys.py** - Contains test cases for the polynomial system solver, which needs additional tests to verify consistent handling of underdetermined systems. ### Key Classes/Functions: - **_solve_reduced_system()** - This function processes polynomial systems and contains the logic error at line 240-243. It incorrectly assumes that having a single univariate polynomial means the system is solvable, without checking if all variables are accounted for. - **solve_poly_system()** - The main entry point for solving polynomial systems that delegates to other specialized solvers, including `_solve_reduced_system()` for general cases. ### Areas of Interest: - The Gröbner basis computation and how it represents underdetermined systems - The univariate polynomial detection logic and how it relates to the overall system dimensionality - The error handling paths for different types of unsolvable or underconstrained systems - The verification logic that should check if the number of equations matches the number of variables ## Fix Hints ### High Confidence Locations: - Line 240-243 in `_solve_reduced_system()`: The condition `if len(univariate) == 1:` needs to be strengthened to `if len(univariate) == 1 and len(gens) == 1:` to ensure it only proceeds with single-variable systems when one univariate equation is found. ### Implementation Hints: - The proposed fix modifies the condition to check both that there is exactly one univariate polynomial AND that there is exactly one generator (variable) - This ensures that single-variable systems are properly solved while underdetermined multi-variable systems are rejected - Consider adding explicit error messages that distinguish between truly unsolvable systems and those with infinite solutions - Add test cases for both `(x - 1,)` and `(y - 1,)` with multiple variables to ensure consistent behavior ### Alternative Hypotheses: - The solver could be enhanced to return parametric solutions for underdetermined systems instead of raising exceptions, representing free variables as parameters - The inconsistency may be related to the order in which variables are processed during the Gröbner basis computation, requiring additional checks throughout the solving pipeline - The detection of zero-dimensional systems might need to be implemented at a higher level, before attempting to compute solutions - The function might benefit from an explicit dimensionality check at the beginning, comparing the number of independent equations to the number of variables
This is not a possible solution i feel , since some of the tests are failing and also weirdly `solve_poly_system([2*x - 3, y*Rational(3, 2) - 2*x, z - 5*y], x, y, z)` is throwing a `NotImplementedError` . Hmm. Well, they should yield similar results: an error or a solution. Looks like maybe a solution, then, should be returned? I am not sure. Maybe @jksuom would have some idea. It seems that the number of polynomials in the Gröbner basis should be the same as the number of variables so there should be something like ``` if len(basis) != len(gens): raise NotImplementedError(...) > It seems that the number of polynomials in the Gröbner basis should be the same as the number of variables This raises a `NotImplementedError` for `solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y)` but which isn't the case since it has a solution. It looks like the test could be `if len(basis) < len(gens)` though I'm not sure if the implementation can handle all cases where `len(basis) > len(gens)`. Yes this works and now `solve_poly_system((y - 1,), x, y)` also returns `NotImplementedError` , I'll open a PR for this. I'm not sure but all cases of `len(basis) > len(gens)` are being handled.
2021-09-02T13:05:27Z
1.9
["test_solve_poly_system"]
["test_solve_biquadratic", "test_solve_triangulated"]
f9a6f50ec0c74d935c50a6e9c9b2cb0469570d91
sympy/sympy
sympy__sympy-22840
d822fcba181155b85ff2b29fe525adbafb22b448
diff --git a/sympy/simplify/cse_main.py b/sympy/simplify/cse_main.py --- a/sympy/simplify/cse_main.py +++ b/sympy/simplify/cse_main.py @@ -567,6 +567,7 @@ def tree_cse(exprs, symbols, opt_subs=None, order='canonical', ignore=()): Substitutions containing any Symbol from ``ignore`` will be ignored. """ from sympy.matrices.expressions import MatrixExpr, MatrixSymbol, MatMul, MatAdd + from sympy.matrices.expressions.matexpr import MatrixElement from sympy.polys.rootoftools import RootOf if opt_subs is None: @@ -586,7 +587,10 @@ def _find_repeated(expr): if isinstance(expr, RootOf): return - if isinstance(expr, Basic) and (expr.is_Atom or expr.is_Order): + if isinstance(expr, Basic) and ( + expr.is_Atom or + expr.is_Order or + isinstance(expr, (MatrixSymbol, MatrixElement))): if expr.is_Symbol: excluded_symbols.add(expr) return
diff --git a/sympy/simplify/tests/test_cse.py b/sympy/simplify/tests/test_cse.py --- a/sympy/simplify/tests/test_cse.py +++ b/sympy/simplify/tests/test_cse.py @@ -347,6 +347,10 @@ def test_cse_MatrixSymbol(): B = MatrixSymbol("B", n, n) assert cse(B) == ([], [B]) + assert cse(A[0] * A[0]) == ([], [A[0]*A[0]]) + + assert cse(A[0,0]*A[0,1] + A[0,0]*A[0,1]*A[0,2]) == ([(x0, A[0, 0]*A[0, 1])], [x0*A[0, 2] + x0]) + def test_cse_MatrixExpr(): A = MatrixSymbol('A', 3, 3) y = MatrixSymbol('y', 3, 1) diff --git a/sympy/utilities/tests/test_codegen.py b/sympy/utilities/tests/test_codegen.py --- a/sympy/utilities/tests/test_codegen.py +++ b/sympy/utilities/tests/test_codegen.py @@ -531,26 +531,9 @@ def test_multidim_c_argument_cse(): '#include "test.h"\n' "#include <math.h>\n" "void c(double *A, double *b, double *out) {\n" - " double x0[9];\n" - " x0[0] = A[0];\n" - " x0[1] = A[1];\n" - " x0[2] = A[2];\n" - " x0[3] = A[3];\n" - " x0[4] = A[4];\n" - " x0[5] = A[5];\n" - " x0[6] = A[6];\n" - " x0[7] = A[7];\n" - " x0[8] = A[8];\n" - " double x1[3];\n" - " x1[0] = b[0];\n" - " x1[1] = b[1];\n" - " x1[2] = b[2];\n" - " const double x2 = x1[0];\n" - " const double x3 = x1[1];\n" - " const double x4 = x1[2];\n" - " out[0] = x2*x0[0] + x3*x0[1] + x4*x0[2];\n" - " out[1] = x2*x0[3] + x3*x0[4] + x4*x0[5];\n" - " out[2] = x2*x0[6] + x3*x0[7] + x4*x0[8];\n" + " out[0] = A[0]*b[0] + A[1]*b[1] + A[2]*b[2];\n" + " out[1] = A[3]*b[0] + A[4]*b[1] + A[5]*b[2];\n" + " out[2] = A[6]*b[0] + A[7]*b[1] + A[8]*b[2];\n" "}\n" ) assert code == expected
# MatrixSymbol Indexing Issue with Common Subexpression Elimination ## Issue Description When using SymPy's Common Subexpression Elimination (`cse()`) with expressions containing indexed MatrixSymbol objects, the function exhibits unexpected behavior. Instead of directly handling matrix element references, CSE generates redundant intermediate expressions by first creating variables for the entire matrices and then creating additional variables for individual matrix elements. This results in inefficient code generation with unnecessary assignments and indirection. The issue specifically occurs in the interaction between the `MatrixSymbol` class and the CSE algorithm, which doesn't properly recognize the relationship between a matrix and its elements. ## Reproduction Steps ```python import sympy as sp from pprint import pprint def sub_in_matrixsymbols(exp, matrices): for matrix in matrices: for i in range(matrix.shape[0]): for j in range(matrix.shape[1]): name = "%s_%d_%d" % (matrix.name, i, j) sym = sp.symbols(name) exp = exp.subs(sym, matrix[i, j]) return exp def t44(name): return sp.Matrix(4, 4, lambda i, j: sp.symbols('%s_%d_%d' % (name, i, j))) # Construct matrices of symbols a = t44("a") b = t44("b") # Set up expression e = a * b # Put in matrixsymbols e2 = sub_in_matrixsymbols(e, [sp.MatrixSymbol("a", 4, 4), sp.MatrixSymbol("b", 4, 4)]) cse_subs, cse_reduced = sp.cse(e2) pprint((cse_subs, cse_reduced)) ``` The CSE output shows: 1. First, it creates variables `x0` and `x2` for the entire matrices `a` and `b` 2. Then it creates variables like `x1 = x0[0, 0]`, `x3 = x2[0, 0]`, etc. for individual matrix elements 3. These matrix elements are then used in expressions, creating unnecessary indirection This happens because: - When CSE traverses the expression tree, it treats the MatrixSymbol itself as a subexpression - Then it separately processes the MatrixElement objects (created via indexing) as different subexpressions - This creates a redundant layering of expressions instead of directly referencing matrix elements ## Expected Behavior CSE should recognize the relationship between MatrixSymbols and their indexed elements, avoiding the creation of unnecessary intermediate variables. When dealing with indexed matrix expressions, CSE should either: 1. Reference the matrix elements directly without creating variables for the entire matrix first 2. Recognize that creating a variable for the entire matrix is unnecessary when only indexed elements are used 3. Have special handling for MatrixElement expressions to optimize the generated code ## Exploration Hints ### Files to Examine: - `sympy/simplify/cse_main.py` - Contains the core CSE implementation that processes expressions and identifies common subexpressions. The issue occurs in how it traverses expression trees containing MatrixElement objects. - `sympy/matrices/expressions/matexpr.py` - Contains the MatrixSymbol class and related functionality for matrix expressions. The way matrix indexing is implemented affects how CSE processes these expressions. - `sympy/matrices/expressions/matexpr.py` - Contains the MatrixElement class that represents indexed elements from a matrix. ### Key Classes/Functions: - `cse()` function - The main entry point for common subexpression elimination that's showing the problematic behavior with matrix indexing. - `MatrixSymbol` class - Represents symbolic matrices; its indexing operation creates MatrixElement objects that aren't being handled correctly by CSE. - `MatrixElement` class - Represents individual elements of a matrix; CSE isn't recognizing its relationship to the parent MatrixSymbol correctly. - `_entry` method in MatrixSymbol - This method handles the creation of MatrixElement objects when indexing operations are performed. ### Areas of Interest: - How CSE determines what constitutes a "common subexpression" when dealing with indexed objects - The relationship between MatrixSymbol and MatrixElement in the expression tree - How matrix indexing operations are represented in the expression tree that CSE traverses - The ordering used to identify and extract subexpressions in the CSE algorithm - How CSE identifies and handles different kinds of operations (like indexing) versus standalone symbols ## Fix Hints ### High Confidence Locations: - `sympy/simplify/cse_main.py` - The optimization process in the CSE algorithm needs to be modified to handle MatrixElement objects specially, recognizing their relationship to the parent MatrixSymbol. - `preprocess_for_cse()` or `tree_cse()` functions in `cse_main.py` - These functions might need modification to better handle matrix indexing operations. ### Implementation Hints: 1. Add special handling for MatrixSymbol and MatrixElement objects in the CSE algorithm: - Detect when expressions contain MatrixElement objects and avoid creating variables for the parent MatrixSymbol - When seeing multiple MatrixElement objects from the same parent, handle them specially 2. Modify how CSE prioritizes subexpressions: - Add a pre-processing step that identifies matrix indexing patterns - Adjust the cost function used to prioritize subexpressions to avoid over-factoring matrix expressions 3. Consider adding an option to CSE to control how matrix indexing is handled: - A flag like `optimize_matrix_indexing=True/False` could let users decide whether matrix indexing should be factored out ### Alternative Hypotheses: 1. The issue might be in how the C code printer interprets the CSE results rather than in CSE itself. The printer might be flattening 2D indices to 1D incorrectly. 2. The problem could be in the `sub_in_matrixsymbols()` function from the example, which might be creating expressions that aren't optimal for CSE processing. 3. The issue might be expected behavior for CSE, and the correct approach could be to apply CSE only after code generation or to use a different optimization strategy for matrix expressions. 4. There could be an architectural disconnect between how SymPy represents matrix operations symbolically and how they're meant to be used in code generation.
Can you create a very simple example using MatrixSymbol and the expected output that you'd like to see? I think one would expect the output to be similar to the following (except for the expression returned by CSE being a matrix where the individual elements are terms as defined by matrix multiplication, that is, unchanged by `cse()`). ```py import sympy as sp from pprint import pprint import sympy.printing.ccode def print_ccode(assign_to, expr): constants, not_c, c_expr = sympy.printing.ccode( expr, human=False, assign_to=assign_to, ) assert not constants, constants assert not not_c, not_c print "%s" % c_expr a = sp.MatrixSymbol("a", 4, 4) b = sp.MatrixSymbol("b", 4, 4) # Set up expression. This is a just a simple example. e = a * b print "\nexpr:" print e cse_subs, cse_reduced = sp.cse(e) print "\ncse(expr):" pprint((cse_subs, cse_reduced)) # Codegen. print "\nccode:" for sym, expr in cse_subs: print_ccode(sympy.printing.ccode(sym), expr) assert len(cse_reduced) == 1 print_ccode(sympy.printing.ccode(sp.symbols("result")), cse_reduced[0]) ``` Gives the output: ``` expr: a*b cse(expr): ([], [a*b]) ccode: result[0] = a[0]*b[0] + a[1]*b[4] + a[2]*b[8] + a[3]*b[12]; result[1] = a[0]*b[1] + a[1]*b[5] + a[2]*b[9] + a[3]*b[13]; result[2] = a[0]*b[2] + a[1]*b[6] + a[2]*b[10] + a[3]*b[14]; result[3] = a[0]*b[3] + a[1]*b[7] + a[2]*b[11] + a[3]*b[15]; result[4] = a[4]*b[0] + a[5]*b[4] + a[6]*b[8] + a[7]*b[12]; result[5] = a[4]*b[1] + a[5]*b[5] + a[6]*b[9] + a[7]*b[13]; result[6] = a[4]*b[2] + a[5]*b[6] + a[6]*b[10] + a[7]*b[14]; result[7] = a[4]*b[3] + a[5]*b[7] + a[6]*b[11] + a[7]*b[15]; result[8] = a[8]*b[0] + a[9]*b[4] + a[10]*b[8] + a[11]*b[12]; result[9] = a[8]*b[1] + a[9]*b[5] + a[10]*b[9] + a[11]*b[13]; result[10] = a[8]*b[2] + a[9]*b[6] + a[10]*b[10] + a[11]*b[14]; result[11] = a[8]*b[3] + a[9]*b[7] + a[10]*b[11] + a[11]*b[15]; result[12] = a[12]*b[0] + a[13]*b[4] + a[14]*b[8] + a[15]*b[12]; result[13] = a[12]*b[1] + a[13]*b[5] + a[14]*b[9] + a[15]*b[13]; result[14] = a[12]*b[2] + a[13]*b[6] + a[14]*b[10] + a[15]*b[14]; result[15] = a[12]*b[3] + a[13]*b[7] + a[14]*b[11] + a[15]*b[15]; ``` Thanks. Note that it doesn't look like cse is well tested (i.e. designed) for MatrixSymbols based on the unit tests: https://github.com/sympy/sympy/blob/master/sympy/simplify/tests/test_cse.py#L315. Those tests don't really prove that it works as desired. So this definitely needs to be fixed. The first part works as expected: ``` In [1]: import sympy as sm In [2]: M = sm.MatrixSymbol('M', 3, 3) In [3]: B = sm.MatrixSymbol('B', 3, 3) In [4]: M * B Out[4]: M*B In [5]: sm.cse(M * B) Out[5]: ([], [M*B]) ``` For the ccode of an expression of MatrixSymbols, I would not expect it to print the results as you have them. MatrixSymbols should map to a matrix algebra library like BLAS and LINPACK. But Matrix, on the other hand, should do what you expect. Note how this works: ``` In [8]: M = sm.Matrix(3, 3, lambda i, j: sm.Symbol('M_{}{}'.format(i, j))) In [9]: M Out[9]: Matrix([ [M_00, M_01, M_02], [M_10, M_11, M_12], [M_20, M_21, M_22]]) In [10]: B = sm.Matrix(3, 3, lambda i, j: sm.Symbol('B_{}{}'.format(i, j))) In [11]: B Out[11]: Matrix([ [B_00, B_01, B_02], [B_10, B_11, B_12], [B_20, B_21, B_22]]) In [12]: M * B Out[12]: Matrix([ [B_00*M_00 + B_10*M_01 + B_20*M_02, B_01*M_00 + B_11*M_01 + B_21*M_02, B_02*M_00 + B_12*M_01 + B_22*M_02], [B_00*M_10 + B_10*M_11 + B_20*M_12, B_01*M_10 + B_11*M_11 + B_21*M_12, B_02*M_10 + B_12*M_11 + B_22*M_12], [B_00*M_20 + B_10*M_21 + B_20*M_22, B_01*M_20 + B_11*M_21 + B_21*M_22, B_02*M_20 + B_12*M_21 + B_22*M_22]]) In [13]: sm.cse(M * B) Out[13]: ([], [Matrix([ [B_00*M_00 + B_10*M_01 + B_20*M_02, B_01*M_00 + B_11*M_01 + B_21*M_02, B_02*M_00 + B_12*M_01 + B_22*M_02], [B_00*M_10 + B_10*M_11 + B_20*M_12, B_01*M_10 + B_11*M_11 + B_21*M_12, B_02*M_10 + B_12*M_11 + B_22*M_12], [B_00*M_20 + B_10*M_21 + B_20*M_22, B_01*M_20 + B_11*M_21 + B_21*M_22, B_02*M_20 + B_12*M_21 + B_22*M_22]])]) In [17]: print(sm.ccode(M * B, assign_to=sm.MatrixSymbol('E', 3, 3))) E[0] = B_00*M_00 + B_10*M_01 + B_20*M_02; E[1] = B_01*M_00 + B_11*M_01 + B_21*M_02; E[2] = B_02*M_00 + B_12*M_01 + B_22*M_02; E[3] = B_00*M_10 + B_10*M_11 + B_20*M_12; E[4] = B_01*M_10 + B_11*M_11 + B_21*M_12; E[5] = B_02*M_10 + B_12*M_11 + B_22*M_12; E[6] = B_00*M_20 + B_10*M_21 + B_20*M_22; E[7] = B_01*M_20 + B_11*M_21 + B_21*M_22; E[8] = B_02*M_20 + B_12*M_21 + B_22*M_22; ``` But in order to get a single input argument from codegen it cannot be different symbols, and if you replace each symbol with a `MatrixSymbol[i, j]` then `cse()` starts doing the above non-optiimizations for some reason. As far as I know, `codegen` does not work with Matrix or MatrixSymbol's in any meaningful way. There are related issues: #11456 #4367 #10522 In general, there needs to be work done in the code generators to properly support matrices. As a work around, I suggest using `ccode` and a custom template to get the result you want.
2022-01-11T17:34:54Z
1.10
["test_cse_MatrixSymbol", "test_multidim_c_argument_cse"]
["test_numbered_symbols", "test_preprocess_for_cse", "test_postprocess_for_cse", "test_cse_single", "test_cse_single2", "test_cse_not_possible", "test_nested_substitution", "test_subtraction_opt", "test_multiple_expressions", "test_bypass_non_commutatives", "test_issue_4498", "test_issue_4020", "test_issue_4203", "test_issue_6263", "test_dont_cse_tuples", "test_pow_invpow", "test_postprocess", "test_issue_4499", "test_issue_6169", "test_cse_Indexed", "test_cse_MatrixExpr", "test_Piecewise", "test_ignore_order_terms", "test_name_conflict", "test_name_conflict_cust_symbols", "test_symbols_exhausted_error", "test_issue_7840", "test_issue_8891", "test_issue_11230", "test_hollow_rejection", "test_cse_ignore", "test_cse_ignore_issue_15002", "test_cse__performance", "test_issue_12070", "test_issue_13000", "test_issue_18203", "test_unevaluated_mul", "test_cse_release_variables", "test_cse_list", "test_issue_18991", "test_Routine_argument_order", "test_empty_c_code", "test_empty_c_code_with_comment", "test_empty_c_header", "test_simple_c_code", "test_c_code_reserved_words", "test_numbersymbol_c_code", "test_c_code_argument_order", "test_simple_c_header", "test_simple_c_codegen", "test_multiple_results_c", "test_no_results_c", "test_ansi_math1_codegen", "test_ansi_math2_codegen", "test_complicated_codegen", "test_loops_c", "test_dummy_loops_c", "test_partial_loops_c", "test_output_arg_c", "test_output_arg_c_reserved_words", "test_ccode_results_named_ordered", "test_ccode_matrixsymbol_slice", "test_ccode_cse", "test_ccode_unused_array_arg", "test_empty_f_code", "test_empty_f_code_with_header", "test_empty_f_header", "test_simple_f_code", "test_numbersymbol_f_code", "test_erf_f_code", "test_f_code_argument_order", "test_simple_f_header", "test_simple_f_codegen", "test_multiple_results_f", "test_no_results_f", "test_intrinsic_math_codegen", "test_intrinsic_math2_codegen", "test_complicated_codegen_f95", "test_loops", "test_dummy_loops_f95", "test_loops_InOut", "test_partial_loops_f", "test_output_arg_f", "test_inline_function", "test_f_code_call_signature_wrap", "test_check_case", "test_check_case_false_positive", "test_c_fortran_omit_routine_name", "test_fcode_matrix_output", "test_fcode_results_named_ordered", "test_fcode_matrixsymbol_slice", "test_fcode_matrixsymbol_slice_autoname", "test_global_vars", "test_custom_codegen", "test_c_with_printer"]
fd40404e72921b9e52a5f9582246e4a6cd96c431