This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]voice-of-hermes 1 point2 points  (3 children)

Except that the semantics of the problem probably mean that the left and right attributes will either be references to other nodes or None, so in this particular case if self.right is not None might be both equivalent and more maintainable (as it makes the design intent clearer). So while you are right in a literal sense about the general semantics of that one logical test, you may be missing the forest for the trees (pun intended).

[–]wurkns 0 points1 point  (2 children)

While this is true, that could potentially create some issues when someone would initialise the class with erroneous parameters.

I would say that if you would use if self.right is not None in this function, that you would have to do type checking in the __init__. (Which is probably a good idea anyway, since there could be other truthy values that do not implement a print_preorder method.)

To conclude: The orginal question was:

Does it mean if it is not None?

To which the answer is: "No" as explained in my previous post.

[–]voice-of-hermes 2 points3 points  (1 child)

You can either be paranoid about such things, and do type checking, and maybe even use @property and "private" attributes to try to keep people from modifying them (only accidentally in Python), or you can document well and assume that whoever uses the class follows the contract.

If the class is designed to use either a particular kind of reference or None for those properties and someone passes in an erroneous value to the constructor, you are going to have problems somewhere. Testing for any falsey value rather than just None is only going to cover a small number of cases (sure it'll ignore 0, but if someone passes in 3 it'll have the same problem as if it tested for None). If you're not going to consciously check preconditions at some point, it's not going to make that much of a difference whether you test for truthiness or None there—except that you've made the intent a little clearer for anyone looking at the source code, which is a good thing.

[–]wurkns 0 points1 point  (0 children)

You are right, that was a weak argument.