Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make sure float infinity/NaN does not trigger B008 #155

Merged
merged 1 commit into from Feb 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 29 additions & 1 deletion bugbear.py
Expand Up @@ -3,6 +3,7 @@
import itertools
import logging
import re
import sys
from collections import namedtuple
from contextlib import suppress
from functools import lru_cache, partial
Expand Down Expand Up @@ -350,7 +351,34 @@ def check_for_b006(self, node):
if call_path in B006.mutable_calls:
self.errors.append(B006(default.lineno, default.col_offset))
elif call_path not in B008.immutable_calls:
self.errors.append(B008(default.lineno, default.col_offset))
# Check if function call is actually a float infinity/NaN literal
if call_path == "float" and len(default.args) == 1:
float_arg = default.args[0]
if sys.version_info < (3, 8, 0):
# NOTE: pre-3.8, string literals are represented with ast.Str
if isinstance(float_arg, ast.Str):
str_val = float_arg.s
else:
str_val = ""
else:
# NOTE: post-3.8, string literals are represented with ast.Constant
if isinstance(float_arg, ast.Constant):
str_val = float_arg.value
if not isinstance(str_val, str):
str_val = ""
else:
str_val = ""

# NOTE: regex derived from documentation at:
# https://docs.python.org/3/library/functions.html#float
inf_nan_regex = r"^[+-]?(inf|infinity|nan)$"
re_result = re.search(inf_nan_regex, str_val.lower())
is_float_literal = re_result is not None
else:
is_float_literal = False

if not is_float_literal:
self.errors.append(B008(default.lineno, default.col_offset))

def check_for_b007(self, node):
targets = NameFinder()
Expand Down
32 changes: 32 additions & 0 deletions tests/b006_b008.py
Expand Up @@ -66,3 +66,35 @@ def kwonlyargs_immutable(*, value=()):

def kwonlyargs_mutable(*, value=[]):
...


def float_inf_okay(value=float("inf")):
pass


def float_infinity_okay(value=float("infinity")):
pass


def float_plus_infinity_okay(value=float("+infinity")):
pass


def float_minus_inf_okay(value=float("-inf")):
pass


def float_nan_okay(value=float("nan")):
pass


def float_minus_NaN_okay(value=float("-NaN")):
pass


def float_int_is_wrong(value=float(3)):
pass


def float_str_not_inf_or_nan_is_wrong(value=float("3.14")):
pass
2 changes: 2 additions & 0 deletions tests/test_bugbear.py
Expand Up @@ -104,6 +104,8 @@ def test_b006_b008(self):
B006(42, 31),
B008(51, 38),
B006(67, 32),
B008(95, 29),
B008(99, 44),
),
)

Expand Down