Python dynamic instantiation from string name of a class in dynamically imported module












133















In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows:



loader-class script:



import sys
class loader:
def __init__(self, module_name, class_name): # both args are strings
try:
__import__(module_name)
modul = sys.modules[module_name]
instance = modul.class_name() # obviously this doesn't works, here is my main problem!
except ImportError:
# manage import error


some-dynamically-loaded-module script:



class myName:
# etc...


I use this arrangement to make any dynamically-loaded-module to be used by the loader-class following certain predefined behaviours in the dyn-loaded-modules...



Any ideas are appreciated.










share|improve this question





























    133















    In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows:



    loader-class script:



    import sys
    class loader:
    def __init__(self, module_name, class_name): # both args are strings
    try:
    __import__(module_name)
    modul = sys.modules[module_name]
    instance = modul.class_name() # obviously this doesn't works, here is my main problem!
    except ImportError:
    # manage import error


    some-dynamically-loaded-module script:



    class myName:
    # etc...


    I use this arrangement to make any dynamically-loaded-module to be used by the loader-class following certain predefined behaviours in the dyn-loaded-modules...



    Any ideas are appreciated.










    share|improve this question



























      133












      133








      133


      46






      In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows:



      loader-class script:



      import sys
      class loader:
      def __init__(self, module_name, class_name): # both args are strings
      try:
      __import__(module_name)
      modul = sys.modules[module_name]
      instance = modul.class_name() # obviously this doesn't works, here is my main problem!
      except ImportError:
      # manage import error


      some-dynamically-loaded-module script:



      class myName:
      # etc...


      I use this arrangement to make any dynamically-loaded-module to be used by the loader-class following certain predefined behaviours in the dyn-loaded-modules...



      Any ideas are appreciated.










      share|improve this question
















      In python, I have to instantiate certain class, knowing its name in a string, but this class 'lives' in a dynamically imported module. An example follows:



      loader-class script:



      import sys
      class loader:
      def __init__(self, module_name, class_name): # both args are strings
      try:
      __import__(module_name)
      modul = sys.modules[module_name]
      instance = modul.class_name() # obviously this doesn't works, here is my main problem!
      except ImportError:
      # manage import error


      some-dynamically-loaded-module script:



      class myName:
      # etc...


      I use this arrangement to make any dynamically-loaded-module to be used by the loader-class following certain predefined behaviours in the dyn-loaded-modules...



      Any ideas are appreciated.







      python






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 31 '16 at 10:09









      Serenity

      17.7k114770




      17.7k114770










      asked Jan 27 '11 at 19:49









      Javier Novoa C.Javier Novoa C.

      2,51483462




      2,51483462
























          6 Answers
          6






          active

          oldest

          votes


















          187














          You can use getattr



          getattr(module, class_name)


          to access the class. More complete code:



          module = __import__(module_name)
          class_ = getattr(module, class_name)
          instance = class_()


          As mentioned below, we may use importlib



          import importlib
          module = importlib.import_module(module_name)
          class_ = getattr(module, class_name)
          instance = class_()





          share|improve this answer





















          • 3





            module = __import__(module, fromlist=[name]) only worked for me.

            – umpirsky
            Jan 9 '12 at 18:18






          • 16





            If anyone is having trouble with the import method Sven mentioned above, I found my code worked better using the following method instead importlib.import_module. Can be used like: module = importlib.import_module(module_name)

            – jpennell
            Nov 27 '12 at 2:37













          • @jpennell you should post that as an answer, it's often more useful to be able to directly use the string returned by obj.__module__

            – Anentropic
            Aug 22 '14 at 12:42











          • importlib.import_module will load the .py file into a pyc if needed as well as handle the complete module.name.pathing.to.get.to.the class. __import__ will not do either of these things, in a django environment (not tested outside of this)

            – James
            Mar 11 '17 at 2:05





















          96














          tl;dr



          Import the root module with importlib.import_module and load the class by its name using getattr function:



          # Standard import
          import importlib
          # Load "module.submodule.MyClass"
          MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
          # Instantiate the class (pass arguments to the constructor, if needed)
          instance = MyClass()


          explanations



          You probably don't want to use __import__ to dynamically import a module by name, as it does not allow you to import submodules:



          >>> mod = __import__("os.path")
          >>> mod.join
          Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
          AttributeError: 'module' object has no attribute 'join'


          Here is what the python doc says about __import__:




          Note: This is an advanced function that is not needed in everyday
          Python programming, unlike importlib.import_module().




          Instead, use the standard importlib module to dynamically import a module by name. With getattr you can then instantiate a class by its name:



          import importlib
          my_module = importlib.import_module("module.submodule")
          MyClass = getattr(my_module, "MyClass")
          instance = MyClass()


          You could also write:



          import importlib
          module_name, class_name = "module.submodule.MyClass".rsplit(".", 1)
          MyClass = getattr(importlib.import_module(module_name), class_name)
          instance = MyClass()


          This code is valid in python ≥ 2.7 (including python 3).






          share|improve this answer


























          • maybe I don't understand your answer, but I have used import to import submodules: __import__("module." + submodule_name_string)

            – Javier Novoa C.
            Jun 25 '15 at 0:16











          • The following code results in an AttributeError: mod = __import__("os.path"); mod.join while the following doesnt: mod = importlib.import_module("os.path"); mod.join

            – Régis B.
            Jun 29 '15 at 6:10













          • oh I see, you're right but I have done the following to get the os.path.join method: getattr(sys.modules["os.path"], "join")

            – Javier Novoa C.
            Jul 1 '15 at 17:55











          • ha! and I see that when using that, then 'import' is unnecessary XD

            – Javier Novoa C.
            Jul 1 '15 at 17:56








          • 1





            The option marked as answer didn't worked for me (using submodules) however this answer does. I think it should be the answer since it's more generic solution for dynamically loading modules.

            – rkachach
            Jul 18 '17 at 9:39



















          11














          Use getattr to get an attribute from a name in a string. In other words, get the instance as



          instance = getattr(modul, class_name)()





          share|improve this answer

































            9














            Copy-paste snippet:



            import importlib
            def str_to_class(module_name, class_name)
            try:
            module_ = importlib.import_module(module_name)
            try:
            class_ = getattr(module_, class_name)()
            except AttributeError:
            logging.error('Class does not exist')
            except ImportError:
            logging.error('Module does not exist')
            return class_ or None





            share|improve this answer

































              5














              If you want this sentence from foo.bar import foo2 to be loaded dynamically, you should do this



              foo = __import__("foo")
              bar = getattr(foo,"bar")
              foo2 = getattr(bar,"foo2")

              instance = foo2()





              share|improve this answer































                2














                I couldn't quite get there in my use case from the examples above, but Ahmad got me the closest (thank you). For those reading this in the future, here is the code that worked for me.



                def get_class(fully_qualified_path, module_name, class_name, *instantiation):
                """
                Returns an instantiated class for the given string descriptors
                :param fully_qualified_path: The path to the module eg("Utilities.Printer")
                :param module_name: The module name eg("Printer")
                :param class_name: The class name eg("ScreenPrinter")
                :param instantiation: Any fields required to instantiate the class
                :return: An instance of the class
                """
                p = __import__(fully_qualified_path)
                m = getattr(p, module_name)
                c = getattr(m, class_name)
                instance = c(*instantiation)
                return instance





                share|improve this answer























                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4821104%2fpython-dynamic-instantiation-from-string-name-of-a-class-in-dynamically-imported%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  6 Answers
                  6






                  active

                  oldest

                  votes








                  6 Answers
                  6






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  187














                  You can use getattr



                  getattr(module, class_name)


                  to access the class. More complete code:



                  module = __import__(module_name)
                  class_ = getattr(module, class_name)
                  instance = class_()


                  As mentioned below, we may use importlib



                  import importlib
                  module = importlib.import_module(module_name)
                  class_ = getattr(module, class_name)
                  instance = class_()





                  share|improve this answer





















                  • 3





                    module = __import__(module, fromlist=[name]) only worked for me.

                    – umpirsky
                    Jan 9 '12 at 18:18






                  • 16





                    If anyone is having trouble with the import method Sven mentioned above, I found my code worked better using the following method instead importlib.import_module. Can be used like: module = importlib.import_module(module_name)

                    – jpennell
                    Nov 27 '12 at 2:37













                  • @jpennell you should post that as an answer, it's often more useful to be able to directly use the string returned by obj.__module__

                    – Anentropic
                    Aug 22 '14 at 12:42











                  • importlib.import_module will load the .py file into a pyc if needed as well as handle the complete module.name.pathing.to.get.to.the class. __import__ will not do either of these things, in a django environment (not tested outside of this)

                    – James
                    Mar 11 '17 at 2:05


















                  187














                  You can use getattr



                  getattr(module, class_name)


                  to access the class. More complete code:



                  module = __import__(module_name)
                  class_ = getattr(module, class_name)
                  instance = class_()


                  As mentioned below, we may use importlib



                  import importlib
                  module = importlib.import_module(module_name)
                  class_ = getattr(module, class_name)
                  instance = class_()





                  share|improve this answer





















                  • 3





                    module = __import__(module, fromlist=[name]) only worked for me.

                    – umpirsky
                    Jan 9 '12 at 18:18






                  • 16





                    If anyone is having trouble with the import method Sven mentioned above, I found my code worked better using the following method instead importlib.import_module. Can be used like: module = importlib.import_module(module_name)

                    – jpennell
                    Nov 27 '12 at 2:37













                  • @jpennell you should post that as an answer, it's often more useful to be able to directly use the string returned by obj.__module__

                    – Anentropic
                    Aug 22 '14 at 12:42











                  • importlib.import_module will load the .py file into a pyc if needed as well as handle the complete module.name.pathing.to.get.to.the class. __import__ will not do either of these things, in a django environment (not tested outside of this)

                    – James
                    Mar 11 '17 at 2:05
















                  187












                  187








                  187







                  You can use getattr



                  getattr(module, class_name)


                  to access the class. More complete code:



                  module = __import__(module_name)
                  class_ = getattr(module, class_name)
                  instance = class_()


                  As mentioned below, we may use importlib



                  import importlib
                  module = importlib.import_module(module_name)
                  class_ = getattr(module, class_name)
                  instance = class_()





                  share|improve this answer















                  You can use getattr



                  getattr(module, class_name)


                  to access the class. More complete code:



                  module = __import__(module_name)
                  class_ = getattr(module, class_name)
                  instance = class_()


                  As mentioned below, we may use importlib



                  import importlib
                  module = importlib.import_module(module_name)
                  class_ = getattr(module, class_name)
                  instance = class_()






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 27 '18 at 2:37









                  Nam G VU

                  13.4k49157285




                  13.4k49157285










                  answered Jan 27 '11 at 19:51









                  Sven MarnachSven Marnach

                  346k77744695




                  346k77744695








                  • 3





                    module = __import__(module, fromlist=[name]) only worked for me.

                    – umpirsky
                    Jan 9 '12 at 18:18






                  • 16





                    If anyone is having trouble with the import method Sven mentioned above, I found my code worked better using the following method instead importlib.import_module. Can be used like: module = importlib.import_module(module_name)

                    – jpennell
                    Nov 27 '12 at 2:37













                  • @jpennell you should post that as an answer, it's often more useful to be able to directly use the string returned by obj.__module__

                    – Anentropic
                    Aug 22 '14 at 12:42











                  • importlib.import_module will load the .py file into a pyc if needed as well as handle the complete module.name.pathing.to.get.to.the class. __import__ will not do either of these things, in a django environment (not tested outside of this)

                    – James
                    Mar 11 '17 at 2:05
















                  • 3





                    module = __import__(module, fromlist=[name]) only worked for me.

                    – umpirsky
                    Jan 9 '12 at 18:18






                  • 16





                    If anyone is having trouble with the import method Sven mentioned above, I found my code worked better using the following method instead importlib.import_module. Can be used like: module = importlib.import_module(module_name)

                    – jpennell
                    Nov 27 '12 at 2:37













                  • @jpennell you should post that as an answer, it's often more useful to be able to directly use the string returned by obj.__module__

                    – Anentropic
                    Aug 22 '14 at 12:42











                  • importlib.import_module will load the .py file into a pyc if needed as well as handle the complete module.name.pathing.to.get.to.the class. __import__ will not do either of these things, in a django environment (not tested outside of this)

                    – James
                    Mar 11 '17 at 2:05










                  3




                  3





                  module = __import__(module, fromlist=[name]) only worked for me.

                  – umpirsky
                  Jan 9 '12 at 18:18





                  module = __import__(module, fromlist=[name]) only worked for me.

                  – umpirsky
                  Jan 9 '12 at 18:18




                  16




                  16





                  If anyone is having trouble with the import method Sven mentioned above, I found my code worked better using the following method instead importlib.import_module. Can be used like: module = importlib.import_module(module_name)

                  – jpennell
                  Nov 27 '12 at 2:37







                  If anyone is having trouble with the import method Sven mentioned above, I found my code worked better using the following method instead importlib.import_module. Can be used like: module = importlib.import_module(module_name)

                  – jpennell
                  Nov 27 '12 at 2:37















                  @jpennell you should post that as an answer, it's often more useful to be able to directly use the string returned by obj.__module__

                  – Anentropic
                  Aug 22 '14 at 12:42





                  @jpennell you should post that as an answer, it's often more useful to be able to directly use the string returned by obj.__module__

                  – Anentropic
                  Aug 22 '14 at 12:42













                  importlib.import_module will load the .py file into a pyc if needed as well as handle the complete module.name.pathing.to.get.to.the class. __import__ will not do either of these things, in a django environment (not tested outside of this)

                  – James
                  Mar 11 '17 at 2:05







                  importlib.import_module will load the .py file into a pyc if needed as well as handle the complete module.name.pathing.to.get.to.the class. __import__ will not do either of these things, in a django environment (not tested outside of this)

                  – James
                  Mar 11 '17 at 2:05















                  96














                  tl;dr



                  Import the root module with importlib.import_module and load the class by its name using getattr function:



                  # Standard import
                  import importlib
                  # Load "module.submodule.MyClass"
                  MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
                  # Instantiate the class (pass arguments to the constructor, if needed)
                  instance = MyClass()


                  explanations



                  You probably don't want to use __import__ to dynamically import a module by name, as it does not allow you to import submodules:



                  >>> mod = __import__("os.path")
                  >>> mod.join
                  Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                  AttributeError: 'module' object has no attribute 'join'


                  Here is what the python doc says about __import__:




                  Note: This is an advanced function that is not needed in everyday
                  Python programming, unlike importlib.import_module().




                  Instead, use the standard importlib module to dynamically import a module by name. With getattr you can then instantiate a class by its name:



                  import importlib
                  my_module = importlib.import_module("module.submodule")
                  MyClass = getattr(my_module, "MyClass")
                  instance = MyClass()


                  You could also write:



                  import importlib
                  module_name, class_name = "module.submodule.MyClass".rsplit(".", 1)
                  MyClass = getattr(importlib.import_module(module_name), class_name)
                  instance = MyClass()


                  This code is valid in python ≥ 2.7 (including python 3).






                  share|improve this answer


























                  • maybe I don't understand your answer, but I have used import to import submodules: __import__("module." + submodule_name_string)

                    – Javier Novoa C.
                    Jun 25 '15 at 0:16











                  • The following code results in an AttributeError: mod = __import__("os.path"); mod.join while the following doesnt: mod = importlib.import_module("os.path"); mod.join

                    – Régis B.
                    Jun 29 '15 at 6:10













                  • oh I see, you're right but I have done the following to get the os.path.join method: getattr(sys.modules["os.path"], "join")

                    – Javier Novoa C.
                    Jul 1 '15 at 17:55











                  • ha! and I see that when using that, then 'import' is unnecessary XD

                    – Javier Novoa C.
                    Jul 1 '15 at 17:56








                  • 1





                    The option marked as answer didn't worked for me (using submodules) however this answer does. I think it should be the answer since it's more generic solution for dynamically loading modules.

                    – rkachach
                    Jul 18 '17 at 9:39
















                  96














                  tl;dr



                  Import the root module with importlib.import_module and load the class by its name using getattr function:



                  # Standard import
                  import importlib
                  # Load "module.submodule.MyClass"
                  MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
                  # Instantiate the class (pass arguments to the constructor, if needed)
                  instance = MyClass()


                  explanations



                  You probably don't want to use __import__ to dynamically import a module by name, as it does not allow you to import submodules:



                  >>> mod = __import__("os.path")
                  >>> mod.join
                  Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                  AttributeError: 'module' object has no attribute 'join'


                  Here is what the python doc says about __import__:




                  Note: This is an advanced function that is not needed in everyday
                  Python programming, unlike importlib.import_module().




                  Instead, use the standard importlib module to dynamically import a module by name. With getattr you can then instantiate a class by its name:



                  import importlib
                  my_module = importlib.import_module("module.submodule")
                  MyClass = getattr(my_module, "MyClass")
                  instance = MyClass()


                  You could also write:



                  import importlib
                  module_name, class_name = "module.submodule.MyClass".rsplit(".", 1)
                  MyClass = getattr(importlib.import_module(module_name), class_name)
                  instance = MyClass()


                  This code is valid in python ≥ 2.7 (including python 3).






                  share|improve this answer


























                  • maybe I don't understand your answer, but I have used import to import submodules: __import__("module." + submodule_name_string)

                    – Javier Novoa C.
                    Jun 25 '15 at 0:16











                  • The following code results in an AttributeError: mod = __import__("os.path"); mod.join while the following doesnt: mod = importlib.import_module("os.path"); mod.join

                    – Régis B.
                    Jun 29 '15 at 6:10













                  • oh I see, you're right but I have done the following to get the os.path.join method: getattr(sys.modules["os.path"], "join")

                    – Javier Novoa C.
                    Jul 1 '15 at 17:55











                  • ha! and I see that when using that, then 'import' is unnecessary XD

                    – Javier Novoa C.
                    Jul 1 '15 at 17:56








                  • 1





                    The option marked as answer didn't worked for me (using submodules) however this answer does. I think it should be the answer since it's more generic solution for dynamically loading modules.

                    – rkachach
                    Jul 18 '17 at 9:39














                  96












                  96








                  96







                  tl;dr



                  Import the root module with importlib.import_module and load the class by its name using getattr function:



                  # Standard import
                  import importlib
                  # Load "module.submodule.MyClass"
                  MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
                  # Instantiate the class (pass arguments to the constructor, if needed)
                  instance = MyClass()


                  explanations



                  You probably don't want to use __import__ to dynamically import a module by name, as it does not allow you to import submodules:



                  >>> mod = __import__("os.path")
                  >>> mod.join
                  Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                  AttributeError: 'module' object has no attribute 'join'


                  Here is what the python doc says about __import__:




                  Note: This is an advanced function that is not needed in everyday
                  Python programming, unlike importlib.import_module().




                  Instead, use the standard importlib module to dynamically import a module by name. With getattr you can then instantiate a class by its name:



                  import importlib
                  my_module = importlib.import_module("module.submodule")
                  MyClass = getattr(my_module, "MyClass")
                  instance = MyClass()


                  You could also write:



                  import importlib
                  module_name, class_name = "module.submodule.MyClass".rsplit(".", 1)
                  MyClass = getattr(importlib.import_module(module_name), class_name)
                  instance = MyClass()


                  This code is valid in python ≥ 2.7 (including python 3).






                  share|improve this answer















                  tl;dr



                  Import the root module with importlib.import_module and load the class by its name using getattr function:



                  # Standard import
                  import importlib
                  # Load "module.submodule.MyClass"
                  MyClass = getattr(importlib.import_module("module.submodule"), "MyClass")
                  # Instantiate the class (pass arguments to the constructor, if needed)
                  instance = MyClass()


                  explanations



                  You probably don't want to use __import__ to dynamically import a module by name, as it does not allow you to import submodules:



                  >>> mod = __import__("os.path")
                  >>> mod.join
                  Traceback (most recent call last):
                  File "<stdin>", line 1, in <module>
                  AttributeError: 'module' object has no attribute 'join'


                  Here is what the python doc says about __import__:




                  Note: This is an advanced function that is not needed in everyday
                  Python programming, unlike importlib.import_module().




                  Instead, use the standard importlib module to dynamically import a module by name. With getattr you can then instantiate a class by its name:



                  import importlib
                  my_module = importlib.import_module("module.submodule")
                  MyClass = getattr(my_module, "MyClass")
                  instance = MyClass()


                  You could also write:



                  import importlib
                  module_name, class_name = "module.submodule.MyClass".rsplit(".", 1)
                  MyClass = getattr(importlib.import_module(module_name), class_name)
                  instance = MyClass()


                  This code is valid in python ≥ 2.7 (including python 3).







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 24 '18 at 8:59

























                  answered Jun 19 '15 at 14:56









                  Régis B.Régis B.

                  5,85533465




                  5,85533465













                  • maybe I don't understand your answer, but I have used import to import submodules: __import__("module." + submodule_name_string)

                    – Javier Novoa C.
                    Jun 25 '15 at 0:16











                  • The following code results in an AttributeError: mod = __import__("os.path"); mod.join while the following doesnt: mod = importlib.import_module("os.path"); mod.join

                    – Régis B.
                    Jun 29 '15 at 6:10













                  • oh I see, you're right but I have done the following to get the os.path.join method: getattr(sys.modules["os.path"], "join")

                    – Javier Novoa C.
                    Jul 1 '15 at 17:55











                  • ha! and I see that when using that, then 'import' is unnecessary XD

                    – Javier Novoa C.
                    Jul 1 '15 at 17:56








                  • 1





                    The option marked as answer didn't worked for me (using submodules) however this answer does. I think it should be the answer since it's more generic solution for dynamically loading modules.

                    – rkachach
                    Jul 18 '17 at 9:39



















                  • maybe I don't understand your answer, but I have used import to import submodules: __import__("module." + submodule_name_string)

                    – Javier Novoa C.
                    Jun 25 '15 at 0:16











                  • The following code results in an AttributeError: mod = __import__("os.path"); mod.join while the following doesnt: mod = importlib.import_module("os.path"); mod.join

                    – Régis B.
                    Jun 29 '15 at 6:10













                  • oh I see, you're right but I have done the following to get the os.path.join method: getattr(sys.modules["os.path"], "join")

                    – Javier Novoa C.
                    Jul 1 '15 at 17:55











                  • ha! and I see that when using that, then 'import' is unnecessary XD

                    – Javier Novoa C.
                    Jul 1 '15 at 17:56








                  • 1





                    The option marked as answer didn't worked for me (using submodules) however this answer does. I think it should be the answer since it's more generic solution for dynamically loading modules.

                    – rkachach
                    Jul 18 '17 at 9:39

















                  maybe I don't understand your answer, but I have used import to import submodules: __import__("module." + submodule_name_string)

                  – Javier Novoa C.
                  Jun 25 '15 at 0:16





                  maybe I don't understand your answer, but I have used import to import submodules: __import__("module." + submodule_name_string)

                  – Javier Novoa C.
                  Jun 25 '15 at 0:16













                  The following code results in an AttributeError: mod = __import__("os.path"); mod.join while the following doesnt: mod = importlib.import_module("os.path"); mod.join

                  – Régis B.
                  Jun 29 '15 at 6:10







                  The following code results in an AttributeError: mod = __import__("os.path"); mod.join while the following doesnt: mod = importlib.import_module("os.path"); mod.join

                  – Régis B.
                  Jun 29 '15 at 6:10















                  oh I see, you're right but I have done the following to get the os.path.join method: getattr(sys.modules["os.path"], "join")

                  – Javier Novoa C.
                  Jul 1 '15 at 17:55





                  oh I see, you're right but I have done the following to get the os.path.join method: getattr(sys.modules["os.path"], "join")

                  – Javier Novoa C.
                  Jul 1 '15 at 17:55













                  ha! and I see that when using that, then 'import' is unnecessary XD

                  – Javier Novoa C.
                  Jul 1 '15 at 17:56







                  ha! and I see that when using that, then 'import' is unnecessary XD

                  – Javier Novoa C.
                  Jul 1 '15 at 17:56






                  1




                  1





                  The option marked as answer didn't worked for me (using submodules) however this answer does. I think it should be the answer since it's more generic solution for dynamically loading modules.

                  – rkachach
                  Jul 18 '17 at 9:39





                  The option marked as answer didn't worked for me (using submodules) however this answer does. I think it should be the answer since it's more generic solution for dynamically loading modules.

                  – rkachach
                  Jul 18 '17 at 9:39











                  11














                  Use getattr to get an attribute from a name in a string. In other words, get the instance as



                  instance = getattr(modul, class_name)()





                  share|improve this answer






























                    11














                    Use getattr to get an attribute from a name in a string. In other words, get the instance as



                    instance = getattr(modul, class_name)()





                    share|improve this answer




























                      11












                      11








                      11







                      Use getattr to get an attribute from a name in a string. In other words, get the instance as



                      instance = getattr(modul, class_name)()





                      share|improve this answer















                      Use getattr to get an attribute from a name in a string. In other words, get the instance as



                      instance = getattr(modul, class_name)()






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jun 1 '13 at 12:36

























                      answered Jan 27 '11 at 19:53









                      AFogliaAFoglia

                      5,73122543




                      5,73122543























                          9














                          Copy-paste snippet:



                          import importlib
                          def str_to_class(module_name, class_name)
                          try:
                          module_ = importlib.import_module(module_name)
                          try:
                          class_ = getattr(module_, class_name)()
                          except AttributeError:
                          logging.error('Class does not exist')
                          except ImportError:
                          logging.error('Module does not exist')
                          return class_ or None





                          share|improve this answer






























                            9














                            Copy-paste snippet:



                            import importlib
                            def str_to_class(module_name, class_name)
                            try:
                            module_ = importlib.import_module(module_name)
                            try:
                            class_ = getattr(module_, class_name)()
                            except AttributeError:
                            logging.error('Class does not exist')
                            except ImportError:
                            logging.error('Module does not exist')
                            return class_ or None





                            share|improve this answer




























                              9












                              9








                              9







                              Copy-paste snippet:



                              import importlib
                              def str_to_class(module_name, class_name)
                              try:
                              module_ = importlib.import_module(module_name)
                              try:
                              class_ = getattr(module_, class_name)()
                              except AttributeError:
                              logging.error('Class does not exist')
                              except ImportError:
                              logging.error('Module does not exist')
                              return class_ or None





                              share|improve this answer















                              Copy-paste snippet:



                              import importlib
                              def str_to_class(module_name, class_name)
                              try:
                              module_ = importlib.import_module(module_name)
                              try:
                              class_ = getattr(module_, class_name)()
                              except AttributeError:
                              logging.error('Class does not exist')
                              except ImportError:
                              logging.error('Module does not exist')
                              return class_ or None






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jul 13 '18 at 10:08









                              user_na

                              236413




                              236413










                              answered Jul 10 '14 at 11:02









                              Andrejs CainikovsAndrejs Cainikovs

                              18.1k25273




                              18.1k25273























                                  5














                                  If you want this sentence from foo.bar import foo2 to be loaded dynamically, you should do this



                                  foo = __import__("foo")
                                  bar = getattr(foo,"bar")
                                  foo2 = getattr(bar,"foo2")

                                  instance = foo2()





                                  share|improve this answer




























                                    5














                                    If you want this sentence from foo.bar import foo2 to be loaded dynamically, you should do this



                                    foo = __import__("foo")
                                    bar = getattr(foo,"bar")
                                    foo2 = getattr(bar,"foo2")

                                    instance = foo2()





                                    share|improve this answer


























                                      5












                                      5








                                      5







                                      If you want this sentence from foo.bar import foo2 to be loaded dynamically, you should do this



                                      foo = __import__("foo")
                                      bar = getattr(foo,"bar")
                                      foo2 = getattr(bar,"foo2")

                                      instance = foo2()





                                      share|improve this answer













                                      If you want this sentence from foo.bar import foo2 to be loaded dynamically, you should do this



                                      foo = __import__("foo")
                                      bar = getattr(foo,"bar")
                                      foo2 = getattr(bar,"foo2")

                                      instance = foo2()






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jan 4 '15 at 13:07









                                      Ahmad MuzakkiAhmad Muzakki

                                      748912




                                      748912























                                          2














                                          I couldn't quite get there in my use case from the examples above, but Ahmad got me the closest (thank you). For those reading this in the future, here is the code that worked for me.



                                          def get_class(fully_qualified_path, module_name, class_name, *instantiation):
                                          """
                                          Returns an instantiated class for the given string descriptors
                                          :param fully_qualified_path: The path to the module eg("Utilities.Printer")
                                          :param module_name: The module name eg("Printer")
                                          :param class_name: The class name eg("ScreenPrinter")
                                          :param instantiation: Any fields required to instantiate the class
                                          :return: An instance of the class
                                          """
                                          p = __import__(fully_qualified_path)
                                          m = getattr(p, module_name)
                                          c = getattr(m, class_name)
                                          instance = c(*instantiation)
                                          return instance





                                          share|improve this answer




























                                            2














                                            I couldn't quite get there in my use case from the examples above, but Ahmad got me the closest (thank you). For those reading this in the future, here is the code that worked for me.



                                            def get_class(fully_qualified_path, module_name, class_name, *instantiation):
                                            """
                                            Returns an instantiated class for the given string descriptors
                                            :param fully_qualified_path: The path to the module eg("Utilities.Printer")
                                            :param module_name: The module name eg("Printer")
                                            :param class_name: The class name eg("ScreenPrinter")
                                            :param instantiation: Any fields required to instantiate the class
                                            :return: An instance of the class
                                            """
                                            p = __import__(fully_qualified_path)
                                            m = getattr(p, module_name)
                                            c = getattr(m, class_name)
                                            instance = c(*instantiation)
                                            return instance





                                            share|improve this answer


























                                              2












                                              2








                                              2







                                              I couldn't quite get there in my use case from the examples above, but Ahmad got me the closest (thank you). For those reading this in the future, here is the code that worked for me.



                                              def get_class(fully_qualified_path, module_name, class_name, *instantiation):
                                              """
                                              Returns an instantiated class for the given string descriptors
                                              :param fully_qualified_path: The path to the module eg("Utilities.Printer")
                                              :param module_name: The module name eg("Printer")
                                              :param class_name: The class name eg("ScreenPrinter")
                                              :param instantiation: Any fields required to instantiate the class
                                              :return: An instance of the class
                                              """
                                              p = __import__(fully_qualified_path)
                                              m = getattr(p, module_name)
                                              c = getattr(m, class_name)
                                              instance = c(*instantiation)
                                              return instance





                                              share|improve this answer













                                              I couldn't quite get there in my use case from the examples above, but Ahmad got me the closest (thank you). For those reading this in the future, here is the code that worked for me.



                                              def get_class(fully_qualified_path, module_name, class_name, *instantiation):
                                              """
                                              Returns an instantiated class for the given string descriptors
                                              :param fully_qualified_path: The path to the module eg("Utilities.Printer")
                                              :param module_name: The module name eg("Printer")
                                              :param class_name: The class name eg("ScreenPrinter")
                                              :param instantiation: Any fields required to instantiate the class
                                              :return: An instance of the class
                                              """
                                              p = __import__(fully_qualified_path)
                                              m = getattr(p, module_name)
                                              c = getattr(m, class_name)
                                              instance = c(*instantiation)
                                              return instance






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Feb 9 '15 at 16:50









                                              SteveJSteveJ

                                              1,2291023




                                              1,2291023






























                                                  draft saved

                                                  draft discarded




















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid



                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4821104%2fpython-dynamic-instantiation-from-string-name-of-a-class-in-dynamically-imported%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                                                  Calculate evaluation metrics using cross_val_predict sklearn

                                                  Insert data from modal to MySQL (multiple modal on website)