Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of python's dir() on dart?

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

like image 583
Otskimanot Sqilal Avatar asked Feb 17 '13 08:02

Otskimanot Sqilal


1 Answers

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.

like image 50
Kai Sellgren Avatar answered Sep 29 '22 04:09

Kai Sellgren