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

I have already seen the following question, but this is not entirely clear to me: How can I get a list of all classes in the current module in Python?

In particular, I do not want to import classes, for example. if I had the following module:

from my.namespace import MyBaseClass from somewhere.else import SomeOtherClass class NewClass(MyBaseClass): pass class AnotherClass(MyBaseClass): pass class YetAnotherClass(MyBaseClass): pass 

If I use clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass) , as the accepted answer suggests in a related question, it will return MyBaseClass and SomeOtherClass in addition to the 3 defined in this module.

How can I get only NewClass , AnotherClass and YetAnotherClass ?

+37
python introspection
Apr 02 2018-11-11T00:
source share
5 answers

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

+23
Apr 02 2018-11-11T00:
source share
— -

I apologize for answering such an old question, but I did not feel comfortable using the validation module for this solution. I read somewhere that was unsafe for use in production.

Initialize all classes in the module to anonymous objects in the list

See Antonis Cristofides's comment on answer 1 .

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

So this is my inexperienced decision

 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) 
+11
Feb 04 '14 at 21:33
source share

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

Since it does not actually execute the module in question (instead, it uses a naive source check), there are some specific methods that it does not quite correctly understand, but for all the "normal" class definitions it describes them exactly.

+7
Apr 02 2018-11-11T00:
source share

I used 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 did not want to enter the name of the current module in

+7
Nov 11 2018-11-11T00:
source share
 from pyclbr import readmodule clsmembers = readmodule(__name__).items() 
+2
Jan 19 '17 at 3:48 on
source share



All Articles