0

I have a module with ~100 classes and I want to get the class whose name matches a string I am supplying.

I used inspect to generate the list of the classes and names, and iterate through that, but is there another way to do it?

What I have:

def get_class_by_name(input_name_string): for (key, cls) in inspect.getmembers(my_module, inspect.isclass): if key == input_name_string: return cls 
6
  • 5
    My only question is: why? Commented Jul 30, 2020 at 13:51
  • 1
    Can you not use getattr(my_module, class_name) to retrieve whatever object has the name of the class you want? Which should be the class object. Commented Jul 30, 2020 at 13:53
  • If there's a shared superclass, you can pull them out of its .__subclasses__(). It would be helpful to give some context on what you're actually trying to achieve, though. Commented Jul 30, 2020 at 13:54
  • vars(my_module)[class_name] would do as well. Commented Jul 30, 2020 at 13:54
  • Are you looking for isinstance() ? Commented Jul 30, 2020 at 13:55

2 Answers 2

2

You can simply use getattr on the module :

import my_module getattr(my_module, class_name) 
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a dictionary for this and the string is always the key to the class.

Here a code:

class A: def __init__(self): self.name = "A" def print(self): print(self.name) class B: def __init__(self, name): self.name = name def print(self): print(self.name) def get_class_by_name(input_name_string, dict): return dict[input_name_string] if __name__ == '__main__': my_classes = {} my_classes["A"] = A() my_classes["B"] = B C = get_class_by_name("A", my_classes) C.print() D = get_class_by_name("B", my_classes)("Hallo") D.print() 

1 Comment

That dict is already a built-in, called globals. Try something like globals()['A'] and see what happens

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.