Skip to content

Commit 2b22f72

Browse files
committed
builtin: add dir builtin
Fixes #12.
1 parent c6c49d2 commit 2b22f72

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

builtin/builtin.go

+34-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ func init() {
3131
py.MustNewMethod("chr", builtin_chr, 0, chr_doc),
3232
py.MustNewMethod("compile", builtin_compile, 0, compile_doc),
3333
// py.MustNewMethod("delattr", builtin_delattr, 0, delattr_doc),
34-
// py.MustNewMethod("dir", builtin_dir, 0, dir_doc),
34+
py.MustNewMethod("dir", builtin_dir, 0, dir_doc),
3535
py.MustNewMethod("divmod", builtin_divmod, 0, divmod_doc),
3636
py.MustNewMethod("eval", py.InternalMethodEval, 0, eval_doc),
3737
py.MustNewMethod("exec", py.InternalMethodExec, 0, exec_doc),
@@ -642,6 +642,39 @@ func builtin_compile(self py.Object, args py.Tuple, kwargs py.StringDict) (py.Ob
642642
return result, nil
643643
}
644644

645+
const dir_doc = `dir([object]) -> list of strings
646+
647+
If called without an argument, return the names in the current scope.
648+
Else, return an alphabetized list of names comprising (some of) the attributes
649+
of the given object, and of attributes reachable from it.
650+
If the object supplies a method named __dir__, it will be used; otherwise
651+
the default dir() logic is used and returns:
652+
for a module object: the module's attributes.
653+
for a class object: its attributes, and recursively the attributes
654+
of its bases.
655+
for any other object: its attributes, its class's attributes, and
656+
recursively the attributes of its class's base classes.
657+
`
658+
659+
func builtin_dir(self py.Object, args py.Tuple) (py.Object, error) {
660+
n, err := args.M__len__()
661+
if err != nil {
662+
return nil, err
663+
}
664+
665+
nn := n.(py.Int)
666+
if nn == 0 {
667+
// list current scope.
668+
panic("dir() not implemented")
669+
}
670+
671+
if nn > 1 {
672+
return nil, py.ExceptionNewf(py.TypeError, "dir expected at most 1 arguments, got %d", nn)
673+
}
674+
675+
panic("dir(n) not implemented")
676+
}
677+
645678
const divmod_doc = `divmod(x, y) -> (quotient, remainder)
646679
647680
Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.`

builtin/tests/builtin.py

+16
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,22 @@
2929
assert code is not None
3030
# FIXME
3131

32+
doc="dir"
33+
def testDir():
34+
a = 1
35+
assert dir() == ["a"]
36+
b = 2
37+
assert dir() == ["a", "b"]
38+
class A:
39+
def method(self): pass
40+
assert "method" in dir(A())
41+
testDir()
42+
try:
43+
dir(1,2,3)
44+
ok=False
45+
except TypeError: ok=True
46+
assert ok, "no exception raised"
47+
3248
doc="divmod"
3349
assert divmod(34,7) == (4, 6)
3450

0 commit comments

Comments
 (0)