Kaushik
Kaushik

Reputation: 1324

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

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 ?

Upvotes: 6

Views: 12293

Answers (2)

Jon Clements
Jon Clements

Reputation: 142136

An alternative that will also find nested classes and doesn't require importing of the file:

source = """
class test:
    class inner_class:
        pass
    pass

class test2:
    pass
"""

import ast
p = ast.parse(source)
classes = [node.name for node in ast.walk(p) if isinstance(node, ast.ClassDef)]
# ['test', 'test2', 'inner_class']

Upvotes: 13

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

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))]

Upvotes: 16

Related Questions