mirror of
https://github.com/pocketpy/pocketpy
synced 2025-10-20 11:30:18 +00:00
add callable
This commit is contained in:
parent
ca2c1a4e9b
commit
b1df516bf1
@ -163,6 +163,17 @@ void init_builtins(VM* _vm) {
|
||||
return args[0];
|
||||
});
|
||||
|
||||
_vm->bind_builtin_func<1>("callable", [](VM* vm, ArgsView args) {
|
||||
PyObject* cls = vm->_t(args[0]);
|
||||
Type t = PK_OBJ_GET(Type, cls);
|
||||
if(t == vm->tp_function) return vm->True;
|
||||
if(t == vm->tp_native_func) return vm->True;
|
||||
if(t == vm->tp_bound_method) return vm->True;
|
||||
if(t == vm->tp_type) return vm->True;
|
||||
bool ok = vm->find_name_in_mro(cls, __call__) != nullptr;
|
||||
return VAR(ok);
|
||||
});
|
||||
|
||||
_vm->bind_builtin_func<1>("__import__", [](VM* vm, ArgsView args) {
|
||||
const Str& name = CAST(Str&, args[0]);
|
||||
auto dot = name.sv().find_last_of(".");
|
||||
@ -1271,12 +1282,20 @@ void init_builtins(VM* _vm) {
|
||||
return VAR(func.decl->signature);
|
||||
});
|
||||
|
||||
// _vm->bind_property(_vm->_t(_vm->tp_function), "__call__", [](VM* vm, ArgsView args) {
|
||||
// return args[0];
|
||||
// });
|
||||
|
||||
_vm->bind_property(_vm->_t(_vm->tp_native_func), "__signature__", [](VM* vm, ArgsView args) {
|
||||
NativeFunc& func = _CAST(NativeFunc&, args[0]);
|
||||
if(func.decl != nullptr) return VAR(func.decl->signature);
|
||||
return VAR("");
|
||||
});
|
||||
|
||||
// _vm->bind_property(_vm->_t(_vm->tp_native_func), "__call__", [](VM* vm, ArgsView args) {
|
||||
// return args[0];
|
||||
// });
|
||||
|
||||
RangeIter::register_class(_vm, _vm->builtins);
|
||||
ArrayIter::register_class(_vm, _vm->builtins);
|
||||
StringIter::register_class(_vm, _vm->builtins);
|
||||
|
@ -1148,3 +1148,26 @@ assert min([
|
||||
(1, 3),
|
||||
(1, 4),
|
||||
]) == (1, 2)
|
||||
|
||||
|
||||
# test callable
|
||||
assert callable(lambda: 1) is True # function
|
||||
assert callable(1) is False # int
|
||||
assert callable(object) is True # type
|
||||
assert callable(object()) is False
|
||||
assert callable([].append) is True # bound method
|
||||
assert callable([].__getitem__) is True # bound method
|
||||
|
||||
class A:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def __call__(self):
|
||||
pass
|
||||
|
||||
assert callable(A) is True # type
|
||||
assert callable(A()) is True # instance with __call__
|
||||
assert callable(A.__call__) is True # bound method
|
||||
assert callable(A.__init__) is True # bound method
|
||||
assert callable(print) is True # builtin function
|
||||
assert callable(isinstance) is True # builtin function
|
||||
|
Loading…
x
Reference in New Issue
Block a user