7

As the title says, is there an equivalent of python's dir() on dart?

Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
Otskimanot Sqilal
  • 2,052
  • 2
  • 18
  • 24

1 Answers1

9

The Python dir() function, is used to find out which names a module defines.

We can use Mirrors and write an equivalent function on our own (or at least very similar):

import 'dart:mirrors';

List<String> dir([String libraryName]) {
  var lib, symbols = [];

  if (?libraryName) {
    lib = currentMirrorSystem().libraries[libraryName];
  } else {
    lib = currentMirrorSystem().isolate.rootLibrary;
  }

  lib.members.forEach((name, mirror) => symbols.add(name));

  return symbols;
}

Now here's an example:

class Hello {}

bar() => print('yay');

main() {
  var foo = 5;

  print(dir()); // [main, bar, Hello, dir]
}

Or specify a library:

print(dir('dart:mirrors'));

[MirroredError, TypeMirror, ObjectMirror, _LazyLibraryMirror, TypeVariableMirror, MirrorException, ClassMirror, MirrorSystem, _LocalMirrorSystemImpl, _LocalVMObjectMirrorImpl, DeclarationMirror, _LazyTypeMirror, _LocalClosureMirrorImpl, mirrorSystemOf, _LazyFunctionTypeMirror, _filterMap, MirroredCompilationError, _Mirrors, _LocalClassMirrorImpl, _LocalInstanceMirrorImpl, _LocalTypedefMirrorImpl, _LocalFunctionTypeMirrorImpl, reflect, MethodMirror, _LocalVariableMirrorImpl, LibraryMirror, _LocalIsolateMirrorImpl, FunctionTypeMirror, _LocalLibraryMirrorImpl, Mirror, _LocalObjectMirrorImpl, _LocalMirrorImpl, _makeSignatureString, _LocalTypeVariableMirrorImpl, Comment, MirroredUncaughtExceptionError, _LocalParameterMirrorImpl, _LazyTypeVariableMirror, TypedefMirror, VariableMirror, IsolateMirror, currentMirrorSystem, _dartEscape, _LocalMethodMirrorImpl, ClosureMirror, VMReference, ParameterMirror, InstanceMirror, _isSimpleValue, SourceLocation]

This literally tells what has been defined in the particular library (module). Now there can be some differences to Python's function, which also seems to sort the names, but this should give you a head-start.

Kai Sellgren
  • 20,678
  • 7
  • 66
  • 80