Fetch __version__ value from file without using imp.load_source?












1















I have previously done the following to fetch a version string:



>>> filepath = './somemodule/__init__.py'
>>> name = 'dummy'
>>> module_source = imp.load_source(name, filepath)
>>> module_source.__version__
1.0.0


Now, when imp has been deprecated in Python 3 (I'm on 3.7.1), what would be a nice replacement for load_source which will just require the std library?



This seems a little convoluted to me AND load_module is actually deprecated:



>>> from importlib.machinery import SourceFileLoader
>>> loaded = SourceFileLoader(name, filepath).load_module()
>>> loaded.__version__
1.0.0


EDIT #1:



This is discussed in Import arbitrary python source file. (Python 3.3+) and one of the solutions which came up there is:



>>> loader = importlib.machinery.SourceFileLoader(name, filepath)
>>> mod = types.ModuleType(loader.name)
>>> loader.exec_module(mod)
>>> mod.__version__
1.0.0









share|improve this question





























    1















    I have previously done the following to fetch a version string:



    >>> filepath = './somemodule/__init__.py'
    >>> name = 'dummy'
    >>> module_source = imp.load_source(name, filepath)
    >>> module_source.__version__
    1.0.0


    Now, when imp has been deprecated in Python 3 (I'm on 3.7.1), what would be a nice replacement for load_source which will just require the std library?



    This seems a little convoluted to me AND load_module is actually deprecated:



    >>> from importlib.machinery import SourceFileLoader
    >>> loaded = SourceFileLoader(name, filepath).load_module()
    >>> loaded.__version__
    1.0.0


    EDIT #1:



    This is discussed in Import arbitrary python source file. (Python 3.3+) and one of the solutions which came up there is:



    >>> loader = importlib.machinery.SourceFileLoader(name, filepath)
    >>> mod = types.ModuleType(loader.name)
    >>> loader.exec_module(mod)
    >>> mod.__version__
    1.0.0









    share|improve this question



























      1












      1








      1








      I have previously done the following to fetch a version string:



      >>> filepath = './somemodule/__init__.py'
      >>> name = 'dummy'
      >>> module_source = imp.load_source(name, filepath)
      >>> module_source.__version__
      1.0.0


      Now, when imp has been deprecated in Python 3 (I'm on 3.7.1), what would be a nice replacement for load_source which will just require the std library?



      This seems a little convoluted to me AND load_module is actually deprecated:



      >>> from importlib.machinery import SourceFileLoader
      >>> loaded = SourceFileLoader(name, filepath).load_module()
      >>> loaded.__version__
      1.0.0


      EDIT #1:



      This is discussed in Import arbitrary python source file. (Python 3.3+) and one of the solutions which came up there is:



      >>> loader = importlib.machinery.SourceFileLoader(name, filepath)
      >>> mod = types.ModuleType(loader.name)
      >>> loader.exec_module(mod)
      >>> mod.__version__
      1.0.0









      share|improve this question
















      I have previously done the following to fetch a version string:



      >>> filepath = './somemodule/__init__.py'
      >>> name = 'dummy'
      >>> module_source = imp.load_source(name, filepath)
      >>> module_source.__version__
      1.0.0


      Now, when imp has been deprecated in Python 3 (I'm on 3.7.1), what would be a nice replacement for load_source which will just require the std library?



      This seems a little convoluted to me AND load_module is actually deprecated:



      >>> from importlib.machinery import SourceFileLoader
      >>> loaded = SourceFileLoader(name, filepath).load_module()
      >>> loaded.__version__
      1.0.0


      EDIT #1:



      This is discussed in Import arbitrary python source file. (Python 3.3+) and one of the solutions which came up there is:



      >>> loader = importlib.machinery.SourceFileLoader(name, filepath)
      >>> mod = types.ModuleType(loader.name)
      >>> loader.exec_module(mod)
      >>> mod.__version__
      1.0.0






      python python-importlib






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 26 '18 at 13:53







      fredrik

















      asked Nov 26 '18 at 13:19









      fredrikfredrik

      3,08343667




      3,08343667
























          2 Answers
          2






          active

          oldest

          votes


















          0














          If you're simply looking to import the version, I usually opt to use utils that are offered from werkzeug; I believe you can use the following:



          from werkzeug.utils import import_string
          version = import_string('module.__version__', silent=True)


          You can also pass silent as a bool, which will tell the function to ignore import errors and return None if any errors are encountered.






          share|improve this answer
























          • Ok, cool. I wonder if there's any way to load the code contents of a file by just using the standard library though.

            – fredrik
            Nov 26 '18 at 13:37













          • Since it's in the init can't you just import it?

            – Julian Camilleri
            Nov 26 '18 at 15:37



















          0














          The "comfortable" way to import a module is to use importlib.import_module(). This is, for all practical purposes, just like using the import statement. However, it cannot import arbitrary files which are not in sys.path, so it doesn't work for your use case.



          To import a file directly, the importlib documentation provides this recipe:




          import importlib.util
          import sys

          # For illustrative purposes.
          import tokenize
          file_path = tokenize.__file__
          module_name = tokenize.__name__

          spec = importlib.util.spec_from_file_location(module_name, file_path)
          module = importlib.util.module_from_spec(spec)
          spec.loader.exec_module(module)
          # Optional; only necessary if you want to be able to import the module
          # by name later.
          sys.modules[module_name] = module



          Finally, a bit of advice: I recommend putting the version string in a separate text file called (say) __version__.txt, and loading it from __init__.py and anything else which needs to know the version. That way, you don't need to execute Python code to read the version number. You can load data from such files by using pkgutil.get_data(__package__, '__version__.txt') in __init__.py, and replace __package__ with a suitable value when calling from another module, or open the file directly. get_data() returns bytes; you may want to call .decode() on the return value to convert it into a string.



          (pkgutil.get_data() may seem a roundabout way to do it, but it's required if your code is imported from a ZIP file or installed in some other exotic way. If your code is in a namespace package or was installed in a particularly unusual fashion, get_data() may fail to work and return None, so you should check for that case and avoid crashing on it.)






          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%2f53482018%2ffetch-version-value-from-file-without-using-imp-load-source%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            If you're simply looking to import the version, I usually opt to use utils that are offered from werkzeug; I believe you can use the following:



            from werkzeug.utils import import_string
            version = import_string('module.__version__', silent=True)


            You can also pass silent as a bool, which will tell the function to ignore import errors and return None if any errors are encountered.






            share|improve this answer
























            • Ok, cool. I wonder if there's any way to load the code contents of a file by just using the standard library though.

              – fredrik
              Nov 26 '18 at 13:37













            • Since it's in the init can't you just import it?

              – Julian Camilleri
              Nov 26 '18 at 15:37
















            0














            If you're simply looking to import the version, I usually opt to use utils that are offered from werkzeug; I believe you can use the following:



            from werkzeug.utils import import_string
            version = import_string('module.__version__', silent=True)


            You can also pass silent as a bool, which will tell the function to ignore import errors and return None if any errors are encountered.






            share|improve this answer
























            • Ok, cool. I wonder if there's any way to load the code contents of a file by just using the standard library though.

              – fredrik
              Nov 26 '18 at 13:37













            • Since it's in the init can't you just import it?

              – Julian Camilleri
              Nov 26 '18 at 15:37














            0












            0








            0







            If you're simply looking to import the version, I usually opt to use utils that are offered from werkzeug; I believe you can use the following:



            from werkzeug.utils import import_string
            version = import_string('module.__version__', silent=True)


            You can also pass silent as a bool, which will tell the function to ignore import errors and return None if any errors are encountered.






            share|improve this answer













            If you're simply looking to import the version, I usually opt to use utils that are offered from werkzeug; I believe you can use the following:



            from werkzeug.utils import import_string
            version = import_string('module.__version__', silent=True)


            You can also pass silent as a bool, which will tell the function to ignore import errors and return None if any errors are encountered.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 26 '18 at 13:28









            Julian CamilleriJulian Camilleri

            1,1531022




            1,1531022













            • Ok, cool. I wonder if there's any way to load the code contents of a file by just using the standard library though.

              – fredrik
              Nov 26 '18 at 13:37













            • Since it's in the init can't you just import it?

              – Julian Camilleri
              Nov 26 '18 at 15:37



















            • Ok, cool. I wonder if there's any way to load the code contents of a file by just using the standard library though.

              – fredrik
              Nov 26 '18 at 13:37













            • Since it's in the init can't you just import it?

              – Julian Camilleri
              Nov 26 '18 at 15:37

















            Ok, cool. I wonder if there's any way to load the code contents of a file by just using the standard library though.

            – fredrik
            Nov 26 '18 at 13:37







            Ok, cool. I wonder if there's any way to load the code contents of a file by just using the standard library though.

            – fredrik
            Nov 26 '18 at 13:37















            Since it's in the init can't you just import it?

            – Julian Camilleri
            Nov 26 '18 at 15:37





            Since it's in the init can't you just import it?

            – Julian Camilleri
            Nov 26 '18 at 15:37













            0














            The "comfortable" way to import a module is to use importlib.import_module(). This is, for all practical purposes, just like using the import statement. However, it cannot import arbitrary files which are not in sys.path, so it doesn't work for your use case.



            To import a file directly, the importlib documentation provides this recipe:




            import importlib.util
            import sys

            # For illustrative purposes.
            import tokenize
            file_path = tokenize.__file__
            module_name = tokenize.__name__

            spec = importlib.util.spec_from_file_location(module_name, file_path)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            # Optional; only necessary if you want to be able to import the module
            # by name later.
            sys.modules[module_name] = module



            Finally, a bit of advice: I recommend putting the version string in a separate text file called (say) __version__.txt, and loading it from __init__.py and anything else which needs to know the version. That way, you don't need to execute Python code to read the version number. You can load data from such files by using pkgutil.get_data(__package__, '__version__.txt') in __init__.py, and replace __package__ with a suitable value when calling from another module, or open the file directly. get_data() returns bytes; you may want to call .decode() on the return value to convert it into a string.



            (pkgutil.get_data() may seem a roundabout way to do it, but it's required if your code is imported from a ZIP file or installed in some other exotic way. If your code is in a namespace package or was installed in a particularly unusual fashion, get_data() may fail to work and return None, so you should check for that case and avoid crashing on it.)






            share|improve this answer






























              0














              The "comfortable" way to import a module is to use importlib.import_module(). This is, for all practical purposes, just like using the import statement. However, it cannot import arbitrary files which are not in sys.path, so it doesn't work for your use case.



              To import a file directly, the importlib documentation provides this recipe:




              import importlib.util
              import sys

              # For illustrative purposes.
              import tokenize
              file_path = tokenize.__file__
              module_name = tokenize.__name__

              spec = importlib.util.spec_from_file_location(module_name, file_path)
              module = importlib.util.module_from_spec(spec)
              spec.loader.exec_module(module)
              # Optional; only necessary if you want to be able to import the module
              # by name later.
              sys.modules[module_name] = module



              Finally, a bit of advice: I recommend putting the version string in a separate text file called (say) __version__.txt, and loading it from __init__.py and anything else which needs to know the version. That way, you don't need to execute Python code to read the version number. You can load data from such files by using pkgutil.get_data(__package__, '__version__.txt') in __init__.py, and replace __package__ with a suitable value when calling from another module, or open the file directly. get_data() returns bytes; you may want to call .decode() on the return value to convert it into a string.



              (pkgutil.get_data() may seem a roundabout way to do it, but it's required if your code is imported from a ZIP file or installed in some other exotic way. If your code is in a namespace package or was installed in a particularly unusual fashion, get_data() may fail to work and return None, so you should check for that case and avoid crashing on it.)






              share|improve this answer




























                0












                0








                0







                The "comfortable" way to import a module is to use importlib.import_module(). This is, for all practical purposes, just like using the import statement. However, it cannot import arbitrary files which are not in sys.path, so it doesn't work for your use case.



                To import a file directly, the importlib documentation provides this recipe:




                import importlib.util
                import sys

                # For illustrative purposes.
                import tokenize
                file_path = tokenize.__file__
                module_name = tokenize.__name__

                spec = importlib.util.spec_from_file_location(module_name, file_path)
                module = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(module)
                # Optional; only necessary if you want to be able to import the module
                # by name later.
                sys.modules[module_name] = module



                Finally, a bit of advice: I recommend putting the version string in a separate text file called (say) __version__.txt, and loading it from __init__.py and anything else which needs to know the version. That way, you don't need to execute Python code to read the version number. You can load data from such files by using pkgutil.get_data(__package__, '__version__.txt') in __init__.py, and replace __package__ with a suitable value when calling from another module, or open the file directly. get_data() returns bytes; you may want to call .decode() on the return value to convert it into a string.



                (pkgutil.get_data() may seem a roundabout way to do it, but it's required if your code is imported from a ZIP file or installed in some other exotic way. If your code is in a namespace package or was installed in a particularly unusual fashion, get_data() may fail to work and return None, so you should check for that case and avoid crashing on it.)






                share|improve this answer















                The "comfortable" way to import a module is to use importlib.import_module(). This is, for all practical purposes, just like using the import statement. However, it cannot import arbitrary files which are not in sys.path, so it doesn't work for your use case.



                To import a file directly, the importlib documentation provides this recipe:




                import importlib.util
                import sys

                # For illustrative purposes.
                import tokenize
                file_path = tokenize.__file__
                module_name = tokenize.__name__

                spec = importlib.util.spec_from_file_location(module_name, file_path)
                module = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(module)
                # Optional; only necessary if you want to be able to import the module
                # by name later.
                sys.modules[module_name] = module



                Finally, a bit of advice: I recommend putting the version string in a separate text file called (say) __version__.txt, and loading it from __init__.py and anything else which needs to know the version. That way, you don't need to execute Python code to read the version number. You can load data from such files by using pkgutil.get_data(__package__, '__version__.txt') in __init__.py, and replace __package__ with a suitable value when calling from another module, or open the file directly. get_data() returns bytes; you may want to call .decode() on the return value to convert it into a string.



                (pkgutil.get_data() may seem a roundabout way to do it, but it's required if your code is imported from a ZIP file or installed in some other exotic way. If your code is in a namespace package or was installed in a particularly unusual fashion, get_data() may fail to work and return None, so you should check for that case and avoid crashing on it.)







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 26 '18 at 14:35

























                answered Nov 26 '18 at 14:10









                KevinKevin

                18.9k53659




                18.9k53659






























                    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%2f53482018%2ffetch-version-value-from-file-without-using-imp-load-source%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)