Why should functions always return the same type?

前端 未结 7 2009
野性不改
野性不改 2020-12-01 03:31

I read somewhere that functions should always return only one type so the following code is considered as bad code:

def x(foo):
 if \'bar\' in foo:
  return          


        
相关标签:
7条回答
  • 2020-12-01 04:16

    It's not so clear that a function must always return objects of a limited type, or that returning None is wrong. For instance, re.search can return a _sre.SRE_Match object or a NoneType object:

    import re
    match=re.search('a','a')
    
    type(match)
    # <type '_sre.SRE_Match'>
    
    match=re.search('a','b')
    
    type(match)
    # <type 'NoneType'>
    

    Designed this way, you can test for a match with the idiom

    if match:
        # do xyz
    

    If the developers had required re.search to return a _sre.SRE_Match object, then the idiom would have to change to

    if match.group(1) is None:
        # do xyz
    

    There would not be any major gain by requiring re.search to always return a _sre.SRE_Match object.

    So I think how you design the function must depend on the situation and in particular, how you plan to use the function.

    Also note that both _sre.SRE_Match and NoneType are instances of object, so in a broad sense they are of the same type. So the rule that "functions should always return only one type" is rather meaningless.

    Having said that, there is a beautiful simplicity to functions that return objects which all share the same properties. (Duck typing, not static typing, is the python way!) It can allow you to chain together functions: foo(bar(baz))) and know with certainty the type of object you'll receive at the other end.

    This can help you check the correctness of your code. By requiring that a function returns only objects of a certain limited type, there are fewer cases to check. "foo always returns an integer, so as long as an integer is expected everywhere I use foo, I'm golden..."

    0 讨论(0)
提交回复
热议问题