1

Is there a way to discover Jython modules inside a package at runtime, if they are inside a Java .jar in the form of compiled .py$class files?

Suppose I have a module foo containing function frobify. Someone else on my team is providing a package bar with modules in it:

bar/
  __init__.py
  tweedledee.py
  tweedledum.py
  walrus.py
  carpenter.py

and they use Jython to compile each of these into a .py$class file, and then turn the bar directory including all .py$class files into bar.jar

Then we run Jython and execute the following:

import foo
import bar

foo.frobify(bar)

where I want to write frobify() to do this:

def frobify(package):
   for module in get_modules(package):
      do_something_with(module)

How could I implement get_modules() so that it returns a list of the modules inside the provided package? I would rather take this approach than having to force my customers to pass in a list of modules explicitly.

Jason S
  • 184,598
  • 164
  • 608
  • 970
  • hmm... I just ran a Jython prompt interactively, and it looks like `dir(package)` includes the modules below it, even if you just import the package itself. – Jason S Aug 16 '18 at 20:15
  • oh, crap, that only works if the package imports its submodules explicitly in __init__.py – Jason S Aug 16 '18 at 20:33

1 Answers1

1

Hmm. Looks like pkgutil can do this:

import sys
import pkgutil

def get_modules():
    pkg = sys.modules[__name__]
    return [importer.find_module(name).load_module(name)
                 for importer, name, ispkg 
                 in pkgutil.iter_modules(pkg.__path__)]

It works in Jython 2.5.3 and Python 2.7.1

Jason S
  • 184,598
  • 164
  • 608
  • 970