I'm developing a Python 2.6 package in which I would like to fetch a list of all classes in a certain directory (within the package) in order to then perform introspection on the class objects.
Specifically, if the directory containing the currently executing module has a sub-dir called 'foobar' and 'foobar' contains .py files specifying class Foo(MyBase)
, class Bar(MyBase)
, and class Bar2
, I want to obtain a list of references to the class objects that inherit from MyBase
, i.e. Foo
and Bar
, but not Bar2
.
I'm not sure if this task actually need involve any dealing with the filesystem or if the modules in the sub-dir are automatically loaded and just need to be listed via introspection somehow. Any ideas here please? Example code is much appreciated, since I'm pretty new to Python, in particular introspection.
To get the class name of an instance in Python: Use the type() function and __name__ to get the type or class of the Object/Instance. Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.
To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .
Modules are never loaded automatically, but it should be easy to iterate over the modules in the directory and load them with the __import__
builtin function:
import os
from glob import glob
for file in glob(os.path.join(os.path.dirname(os.path.abspath(__file__))), "*.py"):
name = os.path.splitext(os.path.basename(file))[0]
# add package prefix to name, if required
module = __import__(name)
for member in dir(module):
# do something with the member named ``member``
I wanted to do the same thing, this is what I ended up with:
import glob
import importlib
import inspect
import os
current_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
current_module_name = os.path.splitext(os.path.basename(current_dir))[0]
for file in glob.glob(current_dir + "/*.py"):
name = os.path.splitext(os.path.basename(file))[0]
# Ignore __ files
if name.startswith("__"):
continue
module = importlib.import_module("." + name,package=current_module_name)
for member in dir(module):
handler_class = getattr(module, member)
if handler_class and inspect.isclass(handler_class):
print member
Hope it helps..
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