I want to know how to get all the classes in the current module as a list

Asked 2 years ago, Updated 2 years ago, 103 views

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

2022-09-21 17:56

1 Answers

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)


2022-09-21 17:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.