Skip to content

Commit c625d39

Browse files
committed
builtin: Implement delattr
1 parent 344a390 commit c625d39

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

builtin/builtin.go

+22-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ func init() {
2929
// py.MustNewMethod("callable", builtin_callable, 0, callable_doc),
3030
py.MustNewMethod("chr", builtin_chr, 0, chr_doc),
3131
py.MustNewMethod("compile", builtin_compile, 0, compile_doc),
32-
// py.MustNewMethod("delattr", builtin_delattr, 0, delattr_doc),
32+
py.MustNewMethod("delattr", builtin_delattr, 0, delattr_doc),
3333
// py.MustNewMethod("dir", builtin_dir, 0, dir_doc),
3434
py.MustNewMethod("divmod", builtin_divmod, 0, divmod_doc),
3535
py.MustNewMethod("eval", py.InternalMethodEval, 0, eval_doc),
@@ -633,6 +633,27 @@ func source_as_string(cmd py.Object, funcname, what string /*, PyCompilerFlags *
633633
// return nil;
634634
}
635635

636+
const delattr_doc = `Deletes the named attribute from the given object.
637+
638+
delattr(x, 'y') is equivalent to "del x.y"
639+
`
640+
641+
func builtin_delattr(self py.Object, args py.Tuple) (py.Object, error) {
642+
var v py.Object
643+
var name py.Object
644+
645+
err := py.UnpackTuple(args, nil, "delattr", 2, 2, &v, &name)
646+
if err != nil {
647+
return nil, err
648+
}
649+
650+
err = py.DeleteAttr(v, name)
651+
if err != nil {
652+
return nil, err
653+
}
654+
return py.None, nil
655+
}
656+
636657
const compile_doc = `compile(source, filename, mode[, flags[, dont_inherit]]) -> code object
637658
638659
Compile the source string (a Python module, statement or expression)

builtin/tests/builtin.py

+9
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,15 @@ class C: pass
300300
setattr(c, "potato", "spud")
301301
assert getattr(c, "potato") == "spud"
302302
assert c.potato == "spud"
303+
delattr(c, "potato")
304+
assert not hasattr(c, "potato")
305+
ok = False
306+
try:
307+
delattr(c, "potato")
308+
except AttributeError as e:
309+
ok = True
310+
finally:
311+
assert ok
303312

304313
doc="sum"
305314
assert sum([1,2,3]) == 6

0 commit comments

Comments
 (0)