Usually, when you get a class as a list within a module, you write it like this
# foo.py
class Foo:
pass
# # test.py
import inspect
import foo
For name, obj in inspect.getmembers(foo): Get class of #foo module
if inspect.isclass(obj):
print(obj) #<class 'foo.Foo'> Output
What I want to know is a list of classes in this module.
# foo.py
import inspect
class Foo:
pass
def print_classes():
for name, obj in inspect.getmembers(???): # ..? What should I do?
if inspect.isclass(obj):
print(obj)
# # test.py
import foo
foo.print_classes()
I'd appreciate it if you could help me because I don't know how to write that annotated part
python reflection inspect
import sys
current_module = sys.modules[__name__]
If you put this in the code,
import sys, inspect
def print_classes():
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(obj):
print(obj)
Make it simpler
clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
© 2024 OneMinuteCode. All rights reserved.