Skip to content

Commit 6d9f9fb

Browse files
committed
Add __bool__ for MetaType
1 parent e303acf commit 6d9f9fb

File tree

4 files changed

+38
-0
lines changed

4 files changed

+38
-0
lines changed

src/embed_tests/ClassManagerTests.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1085,6 +1085,33 @@ def is_enum_value_defined():
10851085
}
10861086
}
10871087

1088+
[Test]
1089+
public void TruthinessCanBeCheckedForTypes()
1090+
{
1091+
using (Py.GIL())
1092+
{
1093+
var module = PyModule.FromString("TruthinessCanBeCheckedForTypes", $@"
1094+
from clr import AddReference
1095+
AddReference(""Python.EmbeddingTest"")
1096+
1097+
from Python.EmbeddingTest import *
1098+
1099+
def throw_if_falsy():
1100+
if not ClassManagerTests:
1101+
raise Exception(""ClassManagerTests is falsy"")
1102+
1103+
def throw_if_not_truthy():
1104+
if ClassManagerTests:
1105+
return
1106+
raise Exception(""ClassManagerTests is not truthy"")
1107+
");
1108+
1109+
// Types are always truthy
1110+
Assert.DoesNotThrow(() => module.InvokeMethod("throw_if_falsy"));
1111+
Assert.DoesNotThrow(() => module.InvokeMethod("throw_if_not_truthy"));
1112+
}
1113+
}
1114+
10881115
private static TestCaseData[] IDictionaryContainsTestCases =>
10891116
[
10901117
new(typeof(TestDictionary<string, string>)),

src/runtime/Native/ITypeOffsets.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ interface ITypeOffsets
3030
int nb_invert { get; }
3131
int nb_inplace_add { get; }
3232
int nb_inplace_subtract { get; }
33+
int nb_bool { get; }
3334
int ob_size { get; }
3435
int ob_type { get; }
3536
int qualname { get; }

src/runtime/Native/TypeOffset.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ static partial class TypeOffset
3737
internal static int nb_invert { get; private set; }
3838
internal static int nb_inplace_add { get; private set; }
3939
internal static int nb_inplace_subtract { get; private set; }
40+
internal static int nb_bool { get; private set; }
4041
internal static int ob_size { get; private set; }
4142
internal static int ob_type { get; private set; }
4243
internal static int qualname { get; private set; }

src/runtime/Types/MetaType.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,15 @@ public static int mp_length(BorrowedReference tp)
386386
return Enum.GetValues(type).Length;
387387
}
388388

389+
/// <summary>
390+
/// Implements __bool__ for types, so that Python uses this instead of __len__ as default.
391+
/// For types, this is always "true"
392+
/// </summary>
393+
public static int nb_bool(BorrowedReference tp)
394+
{
395+
return 1;
396+
}
397+
389398
/// <summary>
390399
/// Implements __contains__ for Enum types.
391400
/// </summary>

0 commit comments

Comments
 (0)