Checking whether type is None

Ian Kelly ian.g.kelly at gmail.com
Wed Jul 25 10:49:29 EDT 2018


On Wed, Jul 25, 2018, 8:27 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))
>

Is there a reason for using singledispatch here rather than a simpler and
more readable "if color is None" check?

>



More information about the Python-list mailing list