• @[email protected]
      link
      fedilink
      English
      013 days ago

      You’d need to explicitly check for None if using the len() construct as well, so this doesn’t change the point of the article.

      • @[email protected]
        link
        fedilink
        English
        1
        edit-2
        13 days ago

        But None has no len

        if not foo:  
        

        -> foo could be an empty list or None, it is ambiguous.

        len(foo) will lead to an exception TypeError if foo is None, I can cleanly catch that.

        It suggests I deal with a boolean when that is not the case. Explicit is better than implicit, and if not foo to check for an empty list may be pythonic, but it’s still implicit af

        • @[email protected]
          link
          fedilink
          English
          013 days ago

          My point is that if your variable can be None then you need the same pattern for the length check.

          So for the Pythonic version:

          if (foo is not None) and not foo:
             ...
          

          For the explicit length check:

          if (foo is not None) and (len(foo) == 0):
            ...
          

          Honestly you’re probably better off using type hints and catching such things with static checks and not adding the None check.

          • @[email protected]
            link
            fedilink
            English
            1
            edit-2
            13 days ago

            This is what I would come up with:

            try:
                if len(foo) == 0:
                ...
            except TypeError:
                ...
            

            There is no need to add a None check, as foo being None should be considered as a faulty input. Avoiding the possibility of foo being None from the beginning using static checks or testing is of course the preferred solution. But in reality we do not work in such optimal environments, at least I can say that from the perspective of data science, where often procedural, untested code is produced that runs only a few times. But I get your point and I think both paths are viable, but I am also okay with being in the wrong here,