6

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 ?

2 Answers 2

16

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))]
Sign up to request clarification or add additional context in comments.

5 Comments

@SanjayT.Sharma oops! typo.
And I would use the classname A instead of so :)
Instead of types and isinstance one can use inspect.isclass instead, which will probably boil down to the same, but is easier to read, imho.
is that possible to get classes by defination order? default is sorted by name.
@metmirr You can get the line number using inspect.getsourcelines and sort the list based on it.
13

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.