I need to get the list of all classes in Python package. At first I get all filenames (it works fine, took it from stackoverflow):
from os import listdir, getcwd
from os.path import isfile, join
mypath = getcwd()
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
Then I inspect all files and it doesn't work properly:
for x in onlyfiles:
for name, obj in inspect.getmembers(x):
if inspect.isclass(obj):
print obj
The output is:
<type 'str'>
....
<type 'str'>
However, the following code works properly:
for name, obj in inspect.getmembers(example.py):
if inspect.isclass(obj):
print obj
Could you help me to figure out what the mistake is?
Using built-in dir() Function To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir(). Example: Python3.
Python __all__ It's a list of public objects of that module, as interpreted by import * . It overrides the default of hiding everything that begins with an underscore.
Get the location of a particular module in Python using the OS module. For a pure Python module, we can locate its source by module_name. __file__. This will return the location where the module's .
Method 1: Using the dir() Function: We have first to import the module in the Python shell, and then we have to write the module name in the dir() method, and it will return the list of all functions present in a particular Python module.
inspect.getmembers()
works on objects, and you are passing in strings. Python doesn't know these strings contain filenames or will treat these filenames as modules to import.
You'd have to import the files for inspect.getmembers()
to work. Because you are working with files in the current directory, you should be able to just import them all:
import importlib
for x in onlyfiles:
module = importlib.import_module(x)
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj):
print obj
Note that inspect.getmembers()
accepts a second argument, the predicate that lets you filter what the method returns. Instead of filtering manually, you could just use inspect.isclass()
as the predicate here:
for x in onlyfiles:
module = importlib.import_module(x)
for name, obj in inspect.getmembers(module, inspect.isclass):
print obj
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With