james
james

Reputation: 1165

list all class names in a package in python

I have a package structure like this:

A/__init__.py
|
 --B/__init__.py
|
 --C/__init__.py

In each package and sub packages, it contains a few classes, e.g. A/__init__.py contains class A1 and A2, B/__init__.py contains class B1 and B2, C/__init__.py contains class C1 and C2. In A/__init__.py, it adds all the class names of A and its sub packages into __all__.

Now, I want to print out all package names as well as their contained class names, e.g.

A contains A1, A2, B contains B1, B2, C contains C1, C2

So given the absolute path of package A, e.g. 'xx/yy/A', how can I print the above line?

My question is not about how to retrieve file path of a package.

Upvotes: 0

Views: 266

Answers (2)

Tony Suffolk 66
Tony Suffolk 66

Reputation: 9724

I will try to dig some code out, but in general :

  1. Walk through the package folders and files using 'os.walk'
  2. For every Python file you find use importlib to import it.
  3. For every imported module use the functions in the 'inspect' standard library module to identify the classes within each imported module.

I don't there is any nice way to import a module based on it's absolute path. The import process works by importing paths which are either relative to the existing module, or relative to an entry in sys.path. An option might be to force add the root of your package into sys.path - and for every file you find work out the dotted module name for the module.

Upvotes: 0

Wayne Werner
Wayne Werner

Reputation: 51907

print(os.path.dirname(os.path.abspath(A.__file__)))

Or did you have something different in mind?

Update:

if package A has not been imported, how can I refer it using A.__file__?

Arguably, there's no easy way to know. You could figure it out by looking at what the import mechanism does and following that to find a folder/file named A.

I only know the absolute folder path of this package.

But that makes it sound like you already know the location of the package on disk and you want to import it, even though it's not installed as a package. You can do something like that, but you shouldn't.

Upvotes: 2

Related Questions