to_bool: avoid creating sets on each call
This commit is contained in:
parent
9cf3d338f4
commit
9e803dd683
|
@ -650,7 +650,7 @@ All objects from ``attrs.converters`` are also available from ``attr.converters`
|
|||
C(x='')
|
||||
|
||||
|
||||
.. autofunction:: attrs.converters.to_bool
|
||||
.. autofunction:: attrs.converters.to_bool(val)
|
||||
|
||||
For example:
|
||||
|
||||
|
@ -665,10 +665,11 @@ All objects from ``attrs.converters`` are also available from ``attr.converters`
|
|||
C(x=True)
|
||||
>>> C(0)
|
||||
C(x=False)
|
||||
>>> C("foo")
|
||||
>>> C("norway")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: Cannot convert value to bool: foo
|
||||
ValueError: Cannot convert value to bool: norway
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -131,15 +131,14 @@ def to_bool(val):
|
|||
"""
|
||||
if isinstance(val, str):
|
||||
val = val.lower()
|
||||
truthy = {True, "true", "t", "yes", "y", "on", "1", 1}
|
||||
falsy = {False, "false", "f", "no", "n", "off", "0", 0}
|
||||
try:
|
||||
if val in truthy:
|
||||
if val in (True, "true", "t", "yes", "y", "on", "1", 1):
|
||||
return True
|
||||
if val in falsy:
|
||||
if val in (False, "false", "f", "no", "n", "off", "0", 0):
|
||||
return False
|
||||
except TypeError:
|
||||
# Raised when "val" is not hashable (e.g., lists)
|
||||
pass
|
||||
msg = f"Cannot convert value to bool: {val}"
|
||||
|
||||
msg = f"Cannot convert value to bool: {val!r}"
|
||||
raise ValueError(msg)
|
||||
|
|
Loading…
Reference in New Issue