Nacromances
Nacromances

Reputation: 23

How to get classes declared in the top level python file

Is there a simple way to retrieve all the classes declared in the top-level python file?

For example :

import inspect                                                                                                          
                                                                                                                                                                                                                                               
class FirstClass:                                                                                                       
    pass                                                                                                                
                                                                                                                         
class SecondClass:                                                                                                      
    pass                                                                                                                
                                                                                                                        
if __name__ == '__main__':                                                                                              
    print(inspect.getmembers(__name__))

I was trying to print FirstClass and SecondClass.

I've tried with inspect module without a success as shown before

I've tried with dir() however it stops working when it is called inside a function.

print(dir())

will result: ['FirstClass', 'SecondClass', 'annotations', 'builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'spec', 'inspect']

The list contains the classes I'am looking for.However when it is called inside another scope like function the result is different.

def getdir():
   print(dir())

it will print an empty list

I've looked at the post however it does not solve the problem when the __name__ is equal '__main__'

How can I get a list of all classes within current module in Python?(How can I get a list of all classes within current module in Python?)

Upvotes: 0

Views: 216

Answers (1)

Julien Palard
Julien Palard

Reputation: 11656

You can use globals() to access your module globals, and inspect to filter for classes only:

import inspect


class FirstClass:
    pass


class SecondClass:
    pass


if __name__ == "__main__":
    print([obj for obj in globals().values() if inspect.isclass(obj)])

But beware, import imports in globals, so if for example you add from gzip import GzipFile you'll get it in the list.

Upvotes: 1

Related Questions