Welcome to my website. I am always posting links to photo albums, art, technology and other creations. Everything that you will see on my numerous personal sites is powered by the formVistaTM Website Management Engine.

icon.linkedin.jpgicon.twitter.jpg

  • Dynamically Instantiating Classes in Python
    08/11/2016 5:52PM
    A common design pattern is to define a class or list of classeses in configuration such that at runtime the classes can be dynamically instantiated.

    I've done this before in many other languages and had need to do so today in Python (2.7.11)

    It seems as though the clean way to do so is by using the Pyton importlib module.  By using it, it enables you to cleanly dynamically import sub modules

    Following is an example:

        import importlib

        klass_1_module = 'some.module.name'
        klass_1_classname = 'KlassNameOne'

        klass_2_module = 'klass2module'
        klass_2_classname = 'KlassNameOne'

        Klass1 = getattr(importlib.import_module(klass_1_module), klass_1_classname)
        klass1_instance = Klass1()

        Klass2 = getattr(importlib.import_module(klass_2_module), klass_2_classname)
        klass2_instance = Klass1('some_arg')
Advanced Search

Categories

Archives