D
D
danyaxaxaxaxa2021-08-11 02:11:59
Python
danyaxaxaxaxa, 2021-08-11 02:11:59

How to simplify a single line if?

Again, I'm trying to learn how to write cleaner code. How can this piece of code be simplified?

if int(conversation_id) != event.object['message']['peer_id'] - 2000000000:
     continue

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Pankov, 2021-08-11
@danyaxaxaxaxa

CONVERSATION2PEER_GAP = 2_000_000_000
conversation_id = int(conversation_id)  # Почему у вас где-то идентификаторы хранятся интом,
# а где-то текстом? Нужно стремиться к стандартизации и избегать таких неконсистентных нюансов.
# Если там не может быть другого текста, то следует приводить к числу сразу когда возможно.
peer_id = event.object['message']['peer_id']
if peer_id != conversation_id + CONVERSATION2PEER_GAP:
     continue

L
LXSTVAYNE, 2021-08-11
@lxstvayne

You can try to write such code for yourself, it seems to me easier to read:

import enum


class SenderType(enum.Enum):
    FROM_USER = enum.auto()
    FROM_CHAT = enum.auto()
    FROM_GROUP = enum.auto()


def get_sender_type(peer_id: int) -> SenderType:
    SHIFT_VALUE = 2_000_000_000

    if peer_id > SHIFT_VALUE:
        return SenderType.FROM_CHAT
    elif 0 < peer_id < SHIFT_VALUE:
        return SenderType.FROM_USER
    else:
        return SenderType.FROM_GROUP


if __name__ == '__main__':
    test_id = 345343111

    if get_sender_type(test_id) == SenderType.FROM_USER:
        print('Работает)')

U
U235U235, 2021-08-11
@U235U235

Not much easier, but as an option:

if sum((int(conversation_id), -event.object['message']['peer_id'], 2e9)):
    continue

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question