Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list of all classes within current module in Python?

I've seen plenty of examples of people extracting all of the classes from a module, usually something like:

# foo.py class Foo:     pass  # test.py import inspect import foo  for name, obj in inspect.getmembers(foo):     if inspect.isclass(obj):         print obj 

Awesome.

But I can't find out how to get all of the classes from the current module.

# foo.py import inspect  class Foo:     pass  def print_classes():     for name, obj in inspect.getmembers(???): # what do I do here?         if inspect.isclass(obj):             print obj  # test.py import foo  foo.print_classes() 

This is probably something really obvious, but I haven't been able to find anything. Can anyone help me out?

like image 383
mcccclean Avatar asked Nov 25 '09 10:11

mcccclean


People also ask

How do you see what is inside a module in Python?

Method 1: Using the dir() Function: We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.

How do I see classes in Python?

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.

Which library function returns the list of all functions in a module in Python?

To list all functions in a Python module you can use dir(module).

What is __ all __ In init py?

In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports.


1 Answers

Try this:

import sys current_module = sys.modules[__name__] 

In your context:

import sys, inspect def print_classes():     for name, obj in inspect.getmembers(sys.modules[__name__]):         if inspect.isclass(obj):             print(obj) 

And even better:

clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass) 

Because inspect.getmembers() takes a predicate.

like image 114
Nadia Alramli Avatar answered Sep 25 '22 08:09

Nadia Alramli