Checking whether type is None

Chris Angelico rosuav at gmail.com
Wed Jul 25 10:36:50 EDT 2018


On Thu, Jul 26, 2018 at 12:20 AM, Stephan Houben
<stephanh42 at gmail.com.invalid> wrote:
> Op 2018-07-24, Chris Angelico schreef <rosuav at gmail.com>:
>> On Wed, Jul 25, 2018 at 9:18 AM, Rob Gaddi
>><rgaddi at highlandtechnology.invalid> wrote:
>>> On 07/24/2018 01:07 PM, Chris Angelico wrote:
>>> I suppose one valid usage would be this sort of thing:
>>>
>>> fn = {
>>>     int: dispatchInt,
>>>     str: dispatchStr,
>>>     list: dispatchList,
>>>     type(None): dispatchNone
>>> }[type(x)]
>>> fn(x)
>>>
>>
>> True, but that would be useful only in a very few situations, where
>> you guarantee that you'll never get any subclasses. So if you're
>> walking something that was decoded from JSON, and you know for certain
>> that you'll only ever get those types (add float to the list and it's
>> basically covered), then yes, you might do this; and then I would say
>> that using "type(None)" is the correct spelling of it.
>
> This is actual code I have:
>
> @singledispatch
> def as_color(color):
>     """Convert object to QColor."""
>     return QtGui.QColor(color)
>
> as_color.register(type(None), lambda x: QtGui.QColor(0, 0, 0, 0))
>

Yep, I would agree with that. If it's type-based dispatch, then
type(None) is the cleanest and easiest way to spell it.

ChrisA


More information about the Python-list mailing list