How do you get all classes defined in a module but not imported?

前端 未结 5 1731
忘掉有多难
忘掉有多难 2020-11-30 11:11

I\'ve already seen the following question but it doesn\'t quite get me where I want: How can I get a list of all classes within current module in Python?

In particul

相关标签:
5条回答
  • 2020-11-30 11:12

    I used the below:

    # Predicate to make sure the classes only come from the module in question
    def pred(c):
        return inspect.isclass(c) and c.__module__ == pred.__module__
    # fetch all members of module __name__ matching 'pred'
    classes = inspect.getmembers(sys.modules[__name__], pred)
    

    I didn't want to type the current module name in

    0 讨论(0)
  • 2020-11-30 11:21

    Inspect the __module__ attribute of the class to find out which module it was defined in.

    0 讨论(0)
  • 2020-11-30 11:25

    I apologize for answering such an old question, but I didn't feel comfortable using the inspect module for this solution. I read somewhere that is wasn't safe to use in production.

    Initialize all the classes in a module into nameless objects in a list

    See Antonis Christofides comment to answer 1.

    I got the answer for testing if an object is a class from How to check whether a variable is a class or not?

    So this is my inspect-free solution

    def classesinmodule(module):
        md = module.__dict__
        return [
            md[c] for c in md if (
                isinstance(md[c], type) and md[c].__module__ == module.__name__
            )
        ]
    
    classesinmodule(modulename)
    
    0 讨论(0)
  • 2020-11-30 11:26
    from pyclbr import readmodule
    
    clsmembers = readmodule(__name__).items()
    
    0 讨论(0)
  • 2020-11-30 11:37

    You may also want to consider using the "Python class browser" module in the standard library: http://docs.python.org/library/pyclbr.html

    Since it doesn't actually execute the module in question (it does naive source inspection instead) there are some specific techniques it doesn't quite understand correctly, but for all "normal" class definitions, it will describe them accurately.

    0 讨论(0)
提交回复
热议问题