Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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 <code>_sre.SRE_Match</code> object or a <code>NoneType</code> object:</p> <pre><code>import re match=re.search('a','a') type(match) # &lt;type '_sre.SRE_Match'&gt; match=re.search('a','b') type(match) # &lt;type 'NoneType'&gt; </code></pre> <p>Designed this way, you can test for a match with the idiom</p> <pre><code>if match: # do xyz </code></pre> <p>If the developers had required re.search to return a <code>_sre.SRE_Match</code> object, then the idiom would have to change to</p> <pre><code>if match.group(1) is None: # do xyz </code></pre> <p>There would not be any major gain by requiring re.search to always return a <code>_sre.SRE_Match</code> object.</p> <p>So I think how you design the function must depend on the situation and in particular, how you plan to use the function.</p> <p>Also note that both <code>_sre.SRE_Match</code> and <code>NoneType</code> 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.</p> <p>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.</p> <p>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..."</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload