re: 4 Useful Things in Python VIEW POST


I appreciate this article. I got me thinking about some of the ways I use python and made me want to make some improvements based on what you have here.

I was looking at your [0] and 0 examples and had a question/comment.
I was tinkering with your foo function and noticed that I could still pass a string in and it would be seen as valid. A string in Python has a length. If I called the function with a string, foo("hello") for example, I would still get the output of "This list contains some items".

foo([0])   # still ok -> "The list contains some items."
foo(0)     # NOT ok -> "We got an empty list."
foo(False) # NOT ok -> "We got an empty list."

def foo(data):
    if len(data) > 0:     # Safer version
        print("The list contains some items.")
        print("We got an empty list.")

I think it may be better to evaluate whether data is truly a list and not empty by doing something like this.

def foo(data):
    if type(data) == list and len(data)>0:     # Safer version
        print("The list contains some items.")
        print("We got an empty or invalid list.")

What do you think? Am I missing something?


Thanks for your comment, I think you are right. If you pass a string to foo() you also get some unexpected behavior. You already posted a remedy to the situation: checking the type of the data argument. That made me think, if there are other ways, that do not rely on type checking. (I know, type checking is not an expensive operation, but still...)

Two more ways, you could alleviate the situation: Working with conventions, if the caller does not respect the contract, they get unexpected behavior:

def foo(alist):
    """This function expects a list."""

Using type hinting: Since Python 3.5 you can specify the type of arguments, and static type checkers can use this information, to determine if you pass the correct types.

def foo(data: list) -> None:
Code of Conduct Report abuse