Paul LaFollette schrieb: > Kind people, > > Using Python 3.0 on a Gatesware machine (XP). > I am building a class in which I want to constrain the types that can > be stored in various instance variables. For instance, I want to be > certain that self.loc contains an int. This is straightforward (as > long as I maintain the discipline of changing loc through a method > rather than just twiddling it directly. > > def setLoc(lo): > assert isinstance(lo, int), "loc must be an int" > self.loc = lo > > does the trick nicely. > > However, I also want to constrain self.next to be either an instance > of class Node, or None. I would think that the following should work > but it doesn't. > > def setNext(nxt): > assert isinstance(nxt, (Node, NoneType)), "next must be a Node" > self.next = nxt
How about the canonical way to check if an object is None? assert Node is None None is a singleton. Python guarantees that there is exactly one None object and on this account only one instance of NoneType. In Python 3.x you can't even overwrite the global variable None. User code shouldn't use NoneType at all. >>> type(None) <class 'NoneType'> >>> type(None)() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot create 'NoneType' instances >>> None = 1 File "<stdin>", line 1 SyntaxError: assignment to keyword The singletons True and False have a similar behavior. It's not possible to overwrite them as well. The bool type always returns either the singleton True or the singleton False. >>> True = False File "<stdin>", line 1 SyntaxError: assignment to keyword >>> type(True) <class 'bool'> >>> type(True) is bool True >>> bool(42) True -- http://mail.python.org/mailman/listinfo/python-list