Simplify chained comparison python что значит

Introduction

In this Pydon’t we will go over the chaining of comparison operators:

Chaining of comparison operators

One of the things I enjoy about Python is that some of its features make so much sense that you don’t even notice that you are using a feature until someone points out that such code wouldn’t work in other languages. One such example is comparison chaining! Look at this snippet of code and tell me if it doesn’t look natural:

In my opinion, this features makes a lot of sense and does not look surprising. Instead, now I feel kind of sad that most languages do not have support for this behaviour.

Another example usage is for when you want to make sure that three values are all the same:

Did you know that you can actually chain an arbitrary number of comparison operators? For example, a == b == c == d == e checks if all five variables are the same, while a checks if you have a strictly increasing sequence.

Pitfalls

Even though this feature looks very sensible, there are a couple of pitfalls you have to look out for.

Non-transitive operators

Non-constant expressions or side-effects

If b contains an expression with side-effects or if it is something that isn’t constant, then the two expressions are not equivalent and you should think about what you are doing.

This snippet shows the difference in number of evaluations of the expression in the middle:

This snippet shows that an expression like 1 can actually evaluate to True when it is unfolded:

The syntax l[::-1] is a “slice” that reverses a list. I’ll be writing about list slicing soon, so stay tuned for that!

Ugly chains

This feature looks really natural, but some particular cases aren’t so great. This is a fairly subjective matter, but I personally don’t love chains where the operators aren’t «aligned», so chains like

look really good, but in my opinion chains like

Now there’s some other chains that are just confusing:

Here is a breakdown of what is happening in the previous example:

Examples in code

Inequality chain

Having a simple utility function that ensures that a given value is between two bounds becomes really simple, e.g.

or if you want to be a little bit more explicit, while also ensuring bounds is a vector with exactly two items (take a look at the Pydon’t about deep unpacking), you can also write

Equality chain

Straight from Python’s enum module, we can find a helper function (that is not exposed to the user), that reads as follows:

This function checks if a string is from a “dunder” method or not.

The first thing the code does is check if the beginning and the ending of the string are the same and equal to «__» :

Conclusion

Here’s the main takeaway of this article, for you, on a silver platter:

“Chaining comparison operators feels so natural, you don’t even notice it is a feature. However, some chains might throw you off if you overlook them.”

This Pydon’t showed you that:

If you liked this Pydon’t be sure to leave a reaction below and share this with your friends and fellow Pythonistas.

References

Online references last consulted on the 1st of March of 2021.

Want to improve your Python 🐍 problem-solving skills? The Python Problem-Solving Bootcamp is just starting! Join now!

Источник

Can you simplify chained comparisons with not equal or equal in Python? [duplicate]

Probably some of you might think this is duplicate, and yes, I found a lot of examples similar to this: Simplify chained comparison python что значит. og0TY. Simplify chained comparison python что значит фото. Simplify chained comparison python что значит-og0TY. картинка Simplify chained comparison python что значит. картинка og0TY

But Pycharm says that I could simply this:

And I did some searching and could not find something similar. My question is it correct to simplify this function like this:

And if so, is it safe and is there is any difference at all between this version and not simplified version except that it’s shorter? If it is not correct way to simplify it, what is then?

1 Answer 1

this is functionnaly equivalent, but when this:

is nice to read, mixing different operators to use chained comparisons isn’t the best choice.

Is that really the same? let’s disassemble to find out:

Surprisingly they aren’t the same, and the chained version has more instructions.

Not sure what’s going on here (some took some more time to explain it better: How do chained comparisons in Python actually work?), but really I’d stick to the and version which shortcuts and is so much readable (think of future maintainers too. ).

That said, one interesting thing about chained comparisons would be if the central argument is computed/takes a long time to compute/has a side effect in the computation and you don’t want to store it in a variable:

Источник

Python-неизвестный

На Хабре уже есть несколько статей\переводов, в которых рассказывается о неизвестных фичах\тонкостях\возможностях Пайтона. Я буду пытаться не повторять их, а дополнять, но если уж так случилось, что вы это уже где-то видели — не огорчайтесь. Я уверен, что найдется что-то интересное и для вас.

Итак, поехали.

Цепочки операторов сравнения (chaining comparison):

Правда и то, что вся магия поломается если добавить скобки:

iter и два параметра

Built-in функция iter возвращает итератор для переданной последовательности. Но, если передавать два параметра, то первый должен быть callable-объектом, а второй — результатом вызова первого объекта, при котором нужно прекратить итерацию. Например, читаем из файла до первой пустой строки:

contextlib

Позволяет легко и красиво пользоваться синтаксисом with EXPR as VAR для своих собственных объектов, функций и т.д. Пример из документации:

Аргументы по умолчанию

Здесь несколько «хаков». Во первых, использование изменяемых (mutable) объектов в качестве аргументов по умолчанию — почти всегда плохая идея:

Почему так? Значения агрументов по умолчанию определяются только раз при создании функции и сохраняются в свойстве func_defaults:

Но есть в довесок и полезный рецепт. Следующий код работает не совсем так, как ожидается:

Поправить его можно просто и элегантно — достаточно заменить lambda: i * 2 на lambda i=i: i * 2:

О именах и привязке к ним можно почитать в Execution Model.

Ellipsis

В зависимости от контекста . (три точки) может быть допустимым синтаксисом. Так, list[. ] передает в функцию __getitem__ объект типа Ellipsis — единственный и неповторимый в своем роде. Демонстрация:

Используется эта прелесть в Numpy.

Обмен значениями переменных

В 10-ом классе нам на уроке информатике предлагали задачку — обменять местами значения двоих переменных, не используя третью. В Пайтоне это даже не вопрос:

Вложенные list comprehensions

В list comprehensions можно использовать несколько for:

Создание нескольких изменяемых объектов

Например, надо создать список из 5 списков. Хочется сделать так:

Лучше наверное вот так:

rot13, string_escape, unicode_escape кодировки

Супер секретный метод шифрования Rot13:

Далее. Например, есть строка из внешнего источника, при этом в строке есть литералы \n, \t, \r и т.п. Как получить отформатированную строку (по сути, сделать безопасный eval)?

unicode_escape работает аналогично, только с юникодом, а не со строками. Так же он умеет превратить строку ‘\u0457’ в букву «ї»:

Перечень поддерживаемых кодировок — standard-encodings.

textwrap

Очень полезная либа для работы с текстами. Делаем с длинной строки много мелких:

Дока — там ещё много вкусного.

itertools

Сплошное умиления. Читать-не перечитать, особенно раздел с рецептами. Здесь вспомню grouper:

фишка в том, что мы работаем с одним итератором

Заключения

Большая часть информации из замечательного топика на StackOverFlow, остальное — собственные наблюдения. На эту тему можно писать много, поэтому старался поделится только самым интересным и полезным.
Спасибо за внимание!
Да прибудет с вами сила документации!

Источник

Русские Блоги

Summary Python Pep8, вызванный методом, может быть статичным

Преступность

Недавно я столкнусь с этой проблемой, когда разработан Python: Pycharm: Метод может быть статичным, проблем нет, но он всегда повлиял на код, как показано ниже

Simplify chained comparison python что значит. 3aa342162e209ea2f4850f2e41f0b047. Simplify chained comparison python что значит фото. Simplify chained comparison python что значит-3aa342162e209ea2f4850f2e41f0b047. картинка Simplify chained comparison python что значит. картинка 3aa342162e209ea2f4850f2e41f0b047

Это потому, что методы, которые мы объявили в классе, не используют переменные в классе. Это говорит нам, что это статический метод и может быть надежно объявлен как статический тип.

Решение следующее: удалить себя в статический метод, тогда вы можете объявить его в этом методе. Как показано ниже:

Simplify chained comparison python что значит. d179a138a6ab696a2da4aeacb6e4bb93. Simplify chained comparison python что значит фото. Simplify chained comparison python что значит-d179a138a6ab696a2da4aeacb6e4bb93. картинка Simplify chained comparison python что значит. картинка d179a138a6ab696a2da4aeacb6e4bb93

Спецификация Pep8

Так что опять же, сделайте больше записей о спецификации кода Python Pep8

Если вы хотите выборочно игнорировать стиль кода PEP8, вы можете использовать следующие методы:

1 сделал мышь на предупреждающее сообщение, нажмите alt+Enter Выберите игнорировать (игнорировать) эту ошибку

Приложение: все предупреждающие данные и соответствующий идентификатор,Официальный адрес: https://pep8.readthedocs.io/en/latest/intro.html# Коды ошибок

Я вообще ленивый, поэтому я рекомендую вам ярлык здесь. Ctrl + alt + L, Спецификация форматирования одной кнопки используется, используется вор, я надеюсь помочь друзьям

Источник

PEP:535
Title:Rich comparison chaining
Author:Nick Coghlan
Status:Deferred
Type:Standards Track
Requires:532
Created:12-Nov-2016
Python-Version:3.8

PEP Deferral

Further consideration of this PEP has been deferred until Python 3.8 at the earliest.

Abstract

Inspired by PEP 335, and building on the circuit breaking protocol described in PEP 532, this PEP proposes a change to the definition of chained comparisons, where the comparison chaining will be updated to use the left-associative circuit breaking operator ( else) rather than the logical disjunction operator ( and) if the left hand comparison returns a circuit breaker as its result.

While there are some practical complexities arising from the current handling of single-valued arrays in NumPy, this change should be sufficient to allow elementwise chained comparison operations for matrices, where the result is a matrix of boolean values, rather than raising ValueError or tautologically returning True (indicating a non-empty matrix).

Relationship with other PEPs

This PEP has been extracted from earlier iterations of PEP 532, as a follow-on use case for the circuit breaking protocol, rather than an essential part of its introduction.

The specific proposal in this PEP to handle the element-wise comparison use case by changing the semantic definition of comparison chaining is drawn directly from Guido’s rejection of PEP 335.

Specification

A chained comparison like 0 else rather than and to implement the comparison chaining:

This allows types like NumPy arrays to control the behaviour of chained comparisons by returning suitably defined circuit breakers from comparison operations.

The expansion of this logic to an arbitrary number of chained comparison operations would be the same as the existing expansion for and.

Rationale

In ultimately rejecting PEP 335, Guido van Rossum noted [1]:

The NumPy folks brought up a somewhat separate issue: for them, the most common use case is chained comparisons (e.g. A a.any() and a.all() can be assured of having the same result:

The proposal in this PEP would allow this situation to be changed by updating the definition of element-wise comparison operations in NumPy to return a dedicated subclass that implements the new circuit breaking protocol and also changes the result array’s interpretation in a boolean context to always return False and hence never trigger the short-circuiting behaviour:

With this change, the chained comparison example above would be able to return:

Implementation

Actual implementation has been deferred pending in-principle interest in the idea of making the changes proposed in PEP 532.

References

Copyright

This document has been placed in the public domain under the terms of the CC0 1.0 license: https://creativecommons.org/publicdomain/zero/1.0/

The PSF

The Python Software Foundation is the organization behind Python. Become a member of the PSF and help advance the software and our mission.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *