Python Any checks too many elements even returning a True option with the first

Asked

Viewed 49 times

4

I’m having a question about how built-in any python:

variavel = None

any([not variavel, variavel.get("chave1"), variavel.get("chave2")])

The way I see it, if the first item on the list was True, the any would already return True and life that follows.

In the documentation itself, shows an example equivalent to what I believed would be the correct behavior.

However, I was testing in the terminal inside the Pycharm:

inserir a descrição da imagem aqui

And apparently, even the first condition returning True, He keeps checking the other items. I believe I’m making some poop, but I’ve tested in other environments and the result I find is the same. All environments are using Python 3.8.3.

  • the problem is not in the logical test. None has no method called get

  • yes, but the doubt arose because this validation rolls within a context that expects a Dict. In the test, I made a request passing None and not {}, hoping that it was exactly the same behavior, after all, as it is inside a any, the first check would already return True, so it doesn’t matter if I use a Dict meodo or any other type, pq in teroria, nor would abter in the next element

  • 3

    I don’t understand why the negatives are a pertinent question. The only problem with the question is error print instead of text.

  • yes.. I did not understand the negatives tbm, but ta good. the print was faltered, should have copied and pasted.

1 answer

7


When you do:

variavel = None

any([not variavel, variavel.get("chave1"), variavel.get("chave2")])

It’s "the same" that you’ve done:

variavel = None
lista = [not variavel, variavel.get("chave1"), variavel.get("chave2")]
any(lista)

The interpreter needs to read, run and create its list before moving to the function any.

If you expect to take advantage of the "short-Circuit" behavior of the language you have two options:

  1. Using IF, so the interpreter does not execute anything after knowing that the result is true. Example:

    variavel = None
    if (
        not variavel
        or variavel.get("chave1")
        or variavel.get("chave2")
    ):
        print(f"Usando IF: True")
    else:
        print(f"Usando IF: False")
    
  2. Using a value generator together with the any, thus the any only reads the first value and already returns the result, never executing the code that generates the error. Example:

    def gera_valores():
        variavel = None
        yield not variavel
        yield variavel.get("chave1")
        yield variavel.get("chave2")
    
    resultado = any(gera_valores())
    print(f"Usando ANY: {resultado!r}")  # True
    

Codes running on Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.