1

I am trying to load a class at run time from a configuration file. The module that contains the class will contain many other classes and I don't want to import them all. The pattern given in this question Import class from module dynamically

cls = getattr(import_module('my_module'), 'my_class')

loads in the entire module which is exactly what I am trying to avoid. Is there way to get just 'my_class' without everything else in 'my_module'?

ztyree
  • 21
  • 3
  • Not really possible, no, not without truly horrible hacks. Why are you trying to avoid importing the entire module? – L3viathan Oct 29 '19 at 12:47
  • 1) I was under the impression that only importing what you need from a module is good form. 2) Other (less savy) users will be able to add classes to this module and I don't know what will happen if two classes end up with the same name. – ztyree Oct 29 '19 at 14:36
  • Re 1: True, but for that you can just do `from my_module import my_class`. Technically all the code in the module will still be executed, but only `my_class` will be visible in the importing module. Re 2: They will also presumably be able to change your existing classes. Maybe them being able to change this is the root of the problem. N.B. If two objects (e.g. classes) are bound to the same name, only the second definition "survives". – L3viathan Oct 29 '19 at 14:40
  • @L3viathan Thanks for the help! unfortunately I cann use 'from a import b' because 'b' is a variable in this project. – ztyree Oct 29 '19 at 16:20
  • `my_class = getattr(__import__("my_module"), "my_class")`? – L3viathan Oct 29 '19 at 20:55

0 Answers0