Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the list of all the class name in a file in python?

Tags:

python

file

class

I am currently writing a python script to display all name of all the python files in a package and also all the name of the class a file contains.

scenario

#A.py

class apple:
      .
      .
class banana:
      .
      .

# Extracting_FilesName_className.py

 f=open("c:/package/A.py','r')     
 className=[]
 "Here i need to use some command to get all the class name within the file A.py and append it to className'  

  print file_name,className 

out put A.py,apple,banana

I can use an old convention way where i could check for each line whether "class" string to is present and retrieve the className. But i want to know is there is a better way to retrieve all the class Name ?

like image 556
Kaushik Avatar asked Nov 30 '22 12:11

Kaushik


1 Answers

Something like this:

>>> from types import ClassType
>>> import A
>>> classes = [x for x in dir(A) if isinstance(getattr(A, x), ClassType)]

Another alternative as @user2033511 suggested:

>>> from inspect import isclass
>>> classes = [x for x in dir(A) if isclass(getattr(A, x))]
like image 52
Ashwini Chaudhary Avatar answered Dec 06 '22 19:12

Ashwini Chaudhary