add pkpy.is_user_defined_type

This commit is contained in:
blueloveTH 2025-04-05 02:26:51 +08:00
parent ddea87e913
commit f99c02abb8
4 changed files with 20 additions and 19 deletions

View File

@ -14,3 +14,6 @@ class TValue[T]:
def memory_usage() -> str: def memory_usage() -> str:
"""Return a summary of the memory usage.""" """Return a summary of the memory usage."""
def is_user_defined_type(t: type) -> bool:
"""Check if a type is user-defined. This means the type was created by executing python `class` statement."""

View File

@ -55,6 +55,14 @@ static bool pkpy_memory_usage(int argc, py_Ref argv) {
return true; return true;
} }
static bool pkpy_is_user_defined_type(int argc, py_Ref argv) {
PY_CHECK_ARGC(1);
PY_CHECK_ARG_TYPE(0, tp_type);
py_TypeInfo* ti = pk__type_info(py_totype(argv));
py_newbool(py_retval(), ti->is_python);
return true;
}
void pk__add_module_pkpy() { void pk__add_module_pkpy() {
py_Ref mod = py_newmodule("pkpy"); py_Ref mod = py_newmodule("pkpy");
@ -90,6 +98,7 @@ void pk__add_module_pkpy() {
py_pop(); py_pop();
py_bindfunc(mod, "memory_usage", pkpy_memory_usage); py_bindfunc(mod, "memory_usage", pkpy_memory_usage);
py_bindfunc(mod, "is_user_defined_type", pkpy_is_user_defined_type);
} }
#undef DEF_TVALUE_METHODS #undef DEF_TVALUE_METHODS

View File

@ -1,19 +0,0 @@
# a = 1
# b = 2
# print(a, b)
# def f(a, b):
# b = a + b
# print(a, b)
# return b
# def g(a, b):
# breakpoint()
# c = f(a, b)
# return c
# g(1, 2)
# f(3, 4)

8
tests/92_pkpy.py Normal file
View File

@ -0,0 +1,8 @@
from pkpy import is_user_defined_type
class A:
pass
assert is_user_defined_type(A)
assert not is_user_defined_type(int)
assert not is_user_defined_type(dict)