Skip to content

Possible code improvement suggestion: Use is not None rather than bool() for None check #32720

Closed
@skasturi

Description

@skasturi

Code Sample, a copy-pastable example if possible

While going through the code I observed at couple of places where bool(o) is being used to check whether the object o is None.

Example 1:

f = lambda x: bool(regex.search(x))

Example 2:
f = lambda x: bool(regex.match(x))

Problem description

bool(o) is several times slower than o is not None (see below). In the above cases however, majority of the time indeed is being taken by the re.search and therefore it might not matter for the overall time. But, why not switch to the possibly correct version?

Moreover, the functionality remains the same as re.search and re.match return None when they cannot find a match; which is fundamentally what is being checked in this code.

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    Code StyleCode style, linting, code_checks

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions