Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 893
Davy8 Avatar asked Apr 02 '11 01:04

Davy8


People also ask

How do you know all the names defined in a module?

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 .

What is __ import __ in Python?

__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.

CAN modules contain classes?

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 .

Can a module have multiple classes?

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.


2 Answers

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

like image 72
Ignacio Vazquez-Abrams Avatar answered Sep 19 '22 13:09

Ignacio Vazquez-Abrams


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) 
like image 40
piRSquared Avatar answered Sep 20 '22 13:09

piRSquared