Pythonic dir(module_name) in Nim?

Viewed 103

To get all available functions from module in Python - pythonistas doing this:

print(dir(module_name))

But how nimjas (ninja like) get this kind of information ?

Additional question:
If python learners - pythonistas
And rust learners - rustarians
Nim --> Nimjas ? :)

2 Answers

It looks like you are trying to retrieve all symbols' names of a module, which as far as I know is not possible in Nim (not yet, at least). There is still an open Pull Request to add this feature, but it hasn't been merged yet: https://github.com/nim-lang/Nim/pull/9560

More information about this in a thread from the Nim forum: https://forum.nim-lang.org/t/7012


However, if you need it for objects, it is possible to use both typeinfo.fields and iterators.fieldPairs (note: modules are not objects in Nim).

Example code for typeinfo.fields:

import typeinfo

type MyObj = object
  a: string
  b: int

var obj = MyObj(a: "asd", b: 123)

for (name, _) in fields(obj.toAny):
  echo name ## will echo "a" and "b"

Example code for iterators.fieldPairs:

type MyObj = object
  a: string
  b: int

var obj = MyObj(a: "asd", b: 123)

for name, value in obj.fieldPairs:
  echo name, ": ", value

⚠️ Note that when using fieldPairs, loop is actually unrolled, as written on official documentation.

Here's an example of fieldPairs used in stdlib (json): lib/pure/json.nim.

Listing the api of a module for humans is a job for documentation

Compile-time reflection of this sort is in general possible with a macro that acts upon parseStmt(staticRead("/path/to/module"))

Here is my answer to this question on rosettacode.

The reason why this sort of spooky-action-at-a-distance isn't made easier by Nim is philosophical rather than technical -- allowing macros to perform arbitrary transformations on source code is a 'with great power comes great responsibility' situation.

with

someMacro:
  statement 1
statement 2

it's clear what can and can't be transformed by someMacro; anything less explicit makes code harder to reason about.

Related