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'?

5
  • Not really possible, no, not without truly horrible hacks. Why are you trying to avoid importing the entire module? Commented Oct 29, 2019 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. Commented Oct 29, 2019 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". Commented Oct 29, 2019 at 14:40
  • @L3viathan Thanks for the help! unfortunately I cann use 'from a import b' because 'b' is a variable in this project. Commented Oct 29, 2019 at 16:20
  • my_class = getattr(__import__("my_module"), "my_class")? Commented Oct 29, 2019 at 20:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.