Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>No, typechecking arguments in Python is not necessary. It is <strong>never</strong> necessary.</p> <p>If your code accepts addresses as rawstring or as a <code>Node</code> object, your design is broken.</p> <p>That comes from the fact that if you don't know already the type of an object in your own program, then you're doing something wrong already.</p> <p>Typechecking hurts code reuse and reduces performance. Having a function that performs different things depending on the type of the object passed is bug-prone and has a behavior harder to understand and maintain.</p> <p>You have following saner options:</p> <ol> <li><p>Make a <code>Node</code> object constructor that accepts rawstrings, or a function that converts strings in <code>Node</code> objects. Make your function assume the argument passed is a <code>Node</code> object. That way, if you need to pass a string to the function, you just do:</p> <pre><code>myfunction(Node(some_string)) </code></pre> <p>That's your best option, it is clean, easy to understand and maintain. Anyone reading the code immediatelly understands what is happening, and you don't have to typecheck.</p></li> <li><p>Make two functions, one that accepts <code>Node</code> objects and one that accepts rawstrings. You can make one call the other internally, in the most convenient way (<code>myfunction_str</code> can create a <code>Node</code> object and call <code>myfunction_node</code>, or the other way around).</p></li> <li><p>Make <code>Node</code> objects have a <code>__str__</code> method and inside your function, call <code>str()</code> on the received argument. That way you always get a string by coercion.</p></li> </ol> <p>In any case, <strong>don't typecheck</strong>. It is completely unnecessary and has only downsides. Refactor your code instead in a way you don't need to typecheck. You only get benefits in doing so, both in short and long run.</p>
 

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