Skip to content

Commit

Permalink
Add option of returning None on failure
Browse files Browse the repository at this point in the history
  • Loading branch information
aragilar committed Jan 26, 2020
1 parent 18fb101 commit e1358b6
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 10 deletions.
2 changes: 1 addition & 1 deletion pylintrc
Expand Up @@ -61,7 +61,7 @@ evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / stateme
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
disable=invalid-name,bad-continuation,too-many-arguments,too-many-locals,too-many-statements,redefined-builtin
disable=invalid-name,bad-continuation,too-many-arguments,too-many-locals,too-many-statements,redefined-builtin,no-else-return


[SIMILARITIES]
Expand Down
33 changes: 24 additions & 9 deletions stringtopy/__init__.py
Expand Up @@ -19,30 +19,42 @@
BOOLEAN_FALSE = {'0', 'no', 'false', 'off', }


def str_to_float_converter():
def str_to_float_converter(use_none_on_fail=False):
"""
Returns a human friendly float converter, currently takes no arguments.
Returns a human friendly float converter, can use use_none_on_fail to
return None if value cannot be converted.
"""
def str_to_float(s):
"""
Convert a string to a float
"""
return float(Fraction(s))
try:
return float(Fraction(s))
except ValueError:
if use_none_on_fail:
return None
raise
return str_to_float


def str_to_int_converter():
def str_to_int_converter(use_none_on_fail=False):
"""
Returns a human friendly int converter, currently takes no arguments.
Returns a human friendly int converter, can use use_none_on_fail to return
None if value cannot be converted.
"""
def str_to_int(s):
"""
Convert a string to a int
"""
frac = Fraction(s)
if frac.denominator == 1:
return int(frac)
raise ValueError("{} is not an integer".format(frac))
try:
frac = Fraction(s)
if frac.denominator == 1:
return int(frac)
raise ValueError("{} is not an integer".format(frac))
except ValueError:
if use_none_on_fail:
return None
raise
return str_to_int


Expand Down Expand Up @@ -79,6 +91,9 @@ def str_to_bool_converter(
)

def str_to_bool(s):
"""
Convert a string to a bool, based on settings
"""
s = s.strip().lower()
if s in boolean_true:
return True
Expand Down
5 changes: 5 additions & 0 deletions tests/test_float.py
@@ -1,12 +1,17 @@
from __future__ import division
import pytest

from stringtopy import str_to_float_converter


def test_not_float(default_str_to_float):
with pytest.raises(ValueError):
default_str_to_float("this is not a float")

def test_not_float_with_none():
str_to_float = str_to_float_converter(use_none_on_fail=True)
assert str_to_float("this is not a float") is None

def test_decimal(default_str_to_float):
assert 1.234 == default_str_to_float("1.234")

Expand Down

0 comments on commit e1358b6

Please sign in to comment.