Question about None
Javier Collado
javier.collado at gmail.com
Fri Jun 12 10:22:05 EDT 2009
Hello,
This should work for you:
In [1]: import types
In [2]: isinstance(None, types.NoneType)
Out[2]: True
Best regards,
Javier
2009/6/12 Paul LaFollette <paul.lafollette at gmail.com>:
> 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
>
> since type(Node) responds with <class, 'NoneType'> but the assertion
> above gives "name 'NoneType' is not defined" suggesting that NoneType
> is some sort of quasi-class.
>
> def setNext(nxt):
> assert nxt==None or isinstance(nxt, Node), "next must be a Node"
> self.next = nxt
>
> works ok, but it's uglier than it ought to be.
>
> So, I have three questions.
>
> 1) Why doesn't isinstance(nxt, (Node, NoneType)) work?
> 2) is their a less ugly alternative that what I am using?
> 3) (this is purely philosophical but I am curious) Would it not be
> more intuitive if
> isinstance(None, <anything at all>) returned true?
>
> Thank you for your kind attention.
> Paul
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list