mercredi 3 mars 2021

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





Aucun commentaire:

Enregistrer un commentaire