Skip to content

Commit e9eaf8c

Browse files
committed
feat(bool): pybool cvt works for Option, bool-able
1 parent 9a8d0dc commit e9eaf8c

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/pylib/pybool.nim

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11

22
from ./collections_abc import Iterable
3+
import ./noneType
4+
import std/options
35

46
type
57
PyBool* = distinct bool
@@ -55,24 +57,36 @@ converter bool*(arg: HasMoreThan): bool = arg > 0 or arg < 0
5557
converter bool*(arg: CanCompToNil): bool = arg != nil
5658
]#
5759

60+
proc optionToBool[T](arg: Option[T]): bool
61+
5862
template toBool*[T](arg: T): bool =
5963
## Converts argument to boolean, checking python-like truthiness.
64+
bind None, isSome, Option, optionToBool
6065
# If we have len proc for this object
6166
when compiles(arg.len):
6267
arg.len > 0
6368
elif T is SomeNumber:
64-
# If we can compare if it's not 0
69+
# If we can compare if it's not 0
6570
arg != 0 # works for NaN
6671
# If we can compare if it's greater than 0
6772
elif compiles(arg > 0):
6873
arg > 0 or arg < 0
6974
# Initialized variables only
7075
elif compiles(arg != nil):
7176
arg != nil
77+
elif compiles(arg != None):
78+
arg != None
79+
elif compiles(bool(arg)):
80+
bool(arg)
81+
elif T is Option:
82+
arg.optionToBool
7283
else:
7384
# XXX: is this correct?
7485
true
7586
87+
proc optionToBool[T](arg: Option[T]): bool =
88+
arg.isSome and arg.unsafeGet.toBool
89+
7690
converter toNimBool*(self): bool = bool(self)
7791
converter pybool*(x: bool): PyBool = PyBool(x)
7892
converter pybool*[T](x: T): PyBool =

0 commit comments

Comments
 (0)