Checking whether type is None

Stephan Houben stephanh42 at gmail.com.invalid
Wed Jul 25 10:20:05 EDT 2018


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))

Stephan


More information about the Python-list mailing list