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 particular, I do not want classes that are imported, e.g. 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)
like the accepted answer in the linked question suggests, it would return MyBaseClass
and SomeOtherClass
in addition to the 3 defined in this module.
How can I get only NewClass
, AnotherClass
and YetAnotherClass
?
The dir() function is used to find out all the names defined in a module. It returns a sorted list of strings containing the names defined in a module. In the output, you can see the names of the functions you defined in the module, add & sub .
__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.
A module can have zero or one or multiple classes. A class can be implemented in one or more . py files (modules). But often, we can organize a set of variables and functions into a class definition or just simply put them in a .
So a module can contain several classes. Whenever you want to use a particular class, import the respective module first and then call the class to make objects.
Inspect the __module__
attribute of the class to find out which module it was defined in.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With