0

I am trying to create an if condition that checks the existence of a certain string and its multiple forms in different lists. The condition currently looks like this.

if ("example_string" in node and "example_string" in node_names) or\
        ("string_similar_to_example_string" in node and
         "string_similar_to_example_string" in node_names):
    return response

Here node is a string that matches the string exactly and node_names is a list of strings that has strings matching the example string. This logic right now works, but I wanted to know if there is a better way to write this that makes it readable and clear.

2 Answers2

1

I like reducing functions like all or any. For instance, I think you could have it done with any and then really just organising the sentence.

E.g,

does_match = False

for string_to_lookup in ["example_string", "string_similar"]:
    does_match = string_to_lookup in node and string_to_lookup in node_names)

return response if does_match else None

Before I go, I want to point out something: I think your condition for matching the list of strings is wrong; At least, it is different from the match against node.

Suppose you have your "example_string", and node is "example_string_yay" and node_names is ["example_string_1", "another_string_bla", "example_what"]. If you do:

>>> res = "example_string" in node and "example_string" in node_names
>>> print(res)
False

but if you do:

>>> res = "example_string" in node and any("example_string" in n for n in node_names)
>>> print(res)
True
Brandt
  • 5,058
  • 3
  • 28
  • 46
  • I see what you are saying. And I think you might just be right about the incorrect matching on ```node_names```. Let me quickly verify this on my end – leslieknope Aug 03 '21 at 11:58
  • Edit: You are right! Thank you sooo much! The second condition was wrong. Sorry my score is wayy too less to even upvote your answer. I shall come back and upvote this once I gain enough reputation! – leslieknope Aug 03 '21 at 12:07
1

As you said, your logic is working here. So, a small function might help with the code readability.

# assuming node and node_names are global here, otherwise you can pass it as well.
def foo(bar):
    """foo function description"""
    if bar in node and bar in node_names:
        return True

if foo("example_string") or foo("string_similar_to_example_string"):
    return response
  • Yep. This makes my code much better to understand. Thank you! But the answer by @brandt below actually pointed out a hole in my comparion. I am accepting this as the answer but I wish I could've accepted that as well!! – leslieknope Aug 03 '21 at 12:05
  • As I did not check for your comparison, just wanted to point out the solution for better readability. Let me upvote his answer for you :). – Muhammad Shoaib Aug 03 '21 at 14:10