How to make global imports from a function?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







50















I fear that this is a messy way to approach the problem but...



let's say that I want to make some imports in Python based on some conditions.



For this reason I want to write a function:



def conditional_import_modules(test):
if test == 'foo':
import onemodule, anothermodule
elif test == 'bar':
import thirdmodule, and_another_module
else:
import all_the_other_modules


Now how can I have the imported modules globally available?



For example:



conditional_import_modules(test='bar')
thirdmodule.myfunction()









share|improve this question




















  • 1





    Can you explain the exact use case for this?

    – sean
    Aug 16 '12 at 15:28






  • 2





    seems like you could just import them all, then only use the modules you need

    – Will
    Aug 16 '12 at 15:30











  • I assume you meant == in your conditions

    – Nicolas Barbey
    Aug 16 '12 at 15:33











  • I don't have a real use case (meaning I can solve in a different way) but this question came in my mind while I was writing some code to import some blueprints based on a configuration file in a flask web-application. I was thinking to write a function to make the imports and another to register them.

    – Giovanni Di Milia
    Aug 16 '12 at 15:37











  • @NicolasBarbey Ops... the fingers are faster than the brain... (corrected)

    – Giovanni Di Milia
    Aug 16 '12 at 15:38


















50















I fear that this is a messy way to approach the problem but...



let's say that I want to make some imports in Python based on some conditions.



For this reason I want to write a function:



def conditional_import_modules(test):
if test == 'foo':
import onemodule, anothermodule
elif test == 'bar':
import thirdmodule, and_another_module
else:
import all_the_other_modules


Now how can I have the imported modules globally available?



For example:



conditional_import_modules(test='bar')
thirdmodule.myfunction()









share|improve this question




















  • 1





    Can you explain the exact use case for this?

    – sean
    Aug 16 '12 at 15:28






  • 2





    seems like you could just import them all, then only use the modules you need

    – Will
    Aug 16 '12 at 15:30











  • I assume you meant == in your conditions

    – Nicolas Barbey
    Aug 16 '12 at 15:33











  • I don't have a real use case (meaning I can solve in a different way) but this question came in my mind while I was writing some code to import some blueprints based on a configuration file in a flask web-application. I was thinking to write a function to make the imports and another to register them.

    – Giovanni Di Milia
    Aug 16 '12 at 15:37











  • @NicolasBarbey Ops... the fingers are faster than the brain... (corrected)

    – Giovanni Di Milia
    Aug 16 '12 at 15:38














50












50








50


8






I fear that this is a messy way to approach the problem but...



let's say that I want to make some imports in Python based on some conditions.



For this reason I want to write a function:



def conditional_import_modules(test):
if test == 'foo':
import onemodule, anothermodule
elif test == 'bar':
import thirdmodule, and_another_module
else:
import all_the_other_modules


Now how can I have the imported modules globally available?



For example:



conditional_import_modules(test='bar')
thirdmodule.myfunction()









share|improve this question
















I fear that this is a messy way to approach the problem but...



let's say that I want to make some imports in Python based on some conditions.



For this reason I want to write a function:



def conditional_import_modules(test):
if test == 'foo':
import onemodule, anothermodule
elif test == 'bar':
import thirdmodule, and_another_module
else:
import all_the_other_modules


Now how can I have the imported modules globally available?



For example:



conditional_import_modules(test='bar')
thirdmodule.myfunction()






python import module python-module






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 23:54









martineau

70.5k1093186




70.5k1093186










asked Aug 16 '12 at 15:26









Giovanni Di MiliaGiovanni Di Milia

4,58294262




4,58294262








  • 1





    Can you explain the exact use case for this?

    – sean
    Aug 16 '12 at 15:28






  • 2





    seems like you could just import them all, then only use the modules you need

    – Will
    Aug 16 '12 at 15:30











  • I assume you meant == in your conditions

    – Nicolas Barbey
    Aug 16 '12 at 15:33











  • I don't have a real use case (meaning I can solve in a different way) but this question came in my mind while I was writing some code to import some blueprints based on a configuration file in a flask web-application. I was thinking to write a function to make the imports and another to register them.

    – Giovanni Di Milia
    Aug 16 '12 at 15:37











  • @NicolasBarbey Ops... the fingers are faster than the brain... (corrected)

    – Giovanni Di Milia
    Aug 16 '12 at 15:38














  • 1





    Can you explain the exact use case for this?

    – sean
    Aug 16 '12 at 15:28






  • 2





    seems like you could just import them all, then only use the modules you need

    – Will
    Aug 16 '12 at 15:30











  • I assume you meant == in your conditions

    – Nicolas Barbey
    Aug 16 '12 at 15:33











  • I don't have a real use case (meaning I can solve in a different way) but this question came in my mind while I was writing some code to import some blueprints based on a configuration file in a flask web-application. I was thinking to write a function to make the imports and another to register them.

    – Giovanni Di Milia
    Aug 16 '12 at 15:37











  • @NicolasBarbey Ops... the fingers are faster than the brain... (corrected)

    – Giovanni Di Milia
    Aug 16 '12 at 15:38








1




1





Can you explain the exact use case for this?

– sean
Aug 16 '12 at 15:28





Can you explain the exact use case for this?

– sean
Aug 16 '12 at 15:28




2




2





seems like you could just import them all, then only use the modules you need

– Will
Aug 16 '12 at 15:30





seems like you could just import them all, then only use the modules you need

– Will
Aug 16 '12 at 15:30













I assume you meant == in your conditions

– Nicolas Barbey
Aug 16 '12 at 15:33





I assume you meant == in your conditions

– Nicolas Barbey
Aug 16 '12 at 15:33













I don't have a real use case (meaning I can solve in a different way) but this question came in my mind while I was writing some code to import some blueprints based on a configuration file in a flask web-application. I was thinking to write a function to make the imports and another to register them.

– Giovanni Di Milia
Aug 16 '12 at 15:37





I don't have a real use case (meaning I can solve in a different way) but this question came in my mind while I was writing some code to import some blueprints based on a configuration file in a flask web-application. I was thinking to write a function to make the imports and another to register them.

– Giovanni Di Milia
Aug 16 '12 at 15:37













@NicolasBarbey Ops... the fingers are faster than the brain... (corrected)

– Giovanni Di Milia
Aug 16 '12 at 15:38





@NicolasBarbey Ops... the fingers are faster than the brain... (corrected)

– Giovanni Di Milia
Aug 16 '12 at 15:38












7 Answers
7






active

oldest

votes


















61














Imported modules are just variables - names bound to some values. So all you need is to import them and make them global with global keyword.



Example:



>>> math
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> def f():
... global math
... import math
...
>>> f()
>>> math
<module 'math' from '/usr/local/lib/python2.6/lib-dynload/math.so'>





share|improve this answer





















  • 4





    Are you sure this is legal? The docs (docs.python.org/2/reference/…) say "Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement." It then says this is not enforced for cpython, but you shouldn't do this.

    – xioxox
    Feb 17 '15 at 9:36











  • global ab.cd raise a SyntaxError

    – V Y
    Jul 18 '16 at 19:00











  • @VY, in that case you would need to use just global ab, as well, cf. my answer

    – maxschlepzig
    Oct 9 '16 at 7:56



















9














You can make the imports global within a function like this:



def my_imports(module_name):
globals()[module_name] = __import__(module_name)





share|improve this answer



















  • 1





    Also, importlib offers a wrapper for __import__ in the import_module function.

    – metakermit
    Sep 2 '14 at 13:57











  • if you do globals()['ab.cd'] = __import__('ab.cd') inside function my_imports, module ab.cd will not be imported

    – V Y
    Jul 18 '16 at 19:03











  • def my_imports(modulename,shortname = None): if shortname is None: shortname = modulename globals()[shortname] = __import__(modulename)

    – mshaffer
    Oct 22 '17 at 19:36











  • my_imports("rpy2")

    – mshaffer
    Oct 22 '17 at 19:36











  • my_imports("numpy","np")

    – mshaffer
    Oct 22 '17 at 19:36



















2














You could have this function return the names of the modules you want to import, and then use



mod == __import__(module_name)





share|improve this answer
























  • I like the approach but your code wouldn't actually work in this case. This code just returns the module but doesn't actually put in the global variables. See my answer for how to do it.

    – badzil
    Aug 16 '12 at 19:46













  • I understand that the response doesn't quite answer the OP's question. However, I generally dislike manipulating globals(). Better to programmatically import the correct modules at the proper scope, IMO (see stackoverflow.com/a/11543718/1332492 for more ranting along these lines)

    – ChrisB
    Aug 16 '12 at 20:11



















2














You can use the built-in function __import__ to conditionally import a module with global scope.



To import a top level module (think: import foo):



def cond_import():
global foo
foo = __import__('foo', globals(), locals())


Import from a hierarchy (think: import foo.bar):



def cond_import():
global foo
foo = __import__('foo.bar', globals(), locals())


Import from a hierarchy and alias (think: import foo.bar as bar):



def cond_import():
global bar
foo = __import__('foo.bar', globals(), locals())
bar = foo.bar





share|improve this answer































    1














    I like @badzil approach.



    def global_imports(modulename,shortname = None, asfunction = False):
    if shortname is None:
    shortname = modulename
    if asfunction is False:
    globals()[shortname] = __import__(modulename)
    else:
    globals()[shortname] = eval(modulename + "." + shortname)


    So something that is traditionally in a class module:



    import numpy as np

    import rpy2
    import rpy2.robjects as robjects
    import rpy2.robjects.packages as rpackages
    from rpy2.robjects.packages import importr


    Can be transformed into a global scope:



    global_imports("numpy","np")

    global_imports("rpy2")
    global_imports("rpy2.robjects","robjects")
    global_imports("rpy2.robjects.packages","rpackages")
    global_imports("rpy2.robjects.packages","importr",True)


    May have some bugs, which I will verify and update. The last example could also have an alias which would be another "shortname" or a hack like "importr|aliasimportr"






    share|improve this answer































      1














      I've just had the similar problem, here is my solution:



      class GlobalImport:

      def __enter__(self):
      return self

      def __call__(self):
      import inspect
      self.collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1].frame).locals

      def __exit__(self, *args):
      globals().update(self.collector)


      then, anywhere in the code:



      with GlobalImport() as gi:
      import os, signal, atexit, threading, _thread
      # whatever you want it won't remain local
      # if only
      gi()
      # is called before the end of this block

      # there you go: use os, signal, ... from whatever place of the module





      share|improve this answer

































        0














        I like @rafał grabie approach. As it even support importing all.
        i.e.
        from os import *



        (Despite it being bad practice XD )



        Not allowed to comment, but here is a python 2.7 version.



        Also removed the need to call the function at the end.



        class GlobalImport:
        def __enter__(self):
        return self
        def __exit__(self, *args):
        import inspect
        collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1][0]).locals
        globals().update(collector)

        def test():
        with GlobalImport() as gi:
        ## will fire a warning as its bad practice for python.
        from os import *

        test()
        print path.exists(__file__)





        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%2f11990556%2fhow-to-make-global-imports-from-a-function%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          61














          Imported modules are just variables - names bound to some values. So all you need is to import them and make them global with global keyword.



          Example:



          >>> math
          Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
          NameError: name 'math' is not defined
          >>> def f():
          ... global math
          ... import math
          ...
          >>> f()
          >>> math
          <module 'math' from '/usr/local/lib/python2.6/lib-dynload/math.so'>





          share|improve this answer





















          • 4





            Are you sure this is legal? The docs (docs.python.org/2/reference/…) say "Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement." It then says this is not enforced for cpython, but you shouldn't do this.

            – xioxox
            Feb 17 '15 at 9:36











          • global ab.cd raise a SyntaxError

            – V Y
            Jul 18 '16 at 19:00











          • @VY, in that case you would need to use just global ab, as well, cf. my answer

            – maxschlepzig
            Oct 9 '16 at 7:56
















          61














          Imported modules are just variables - names bound to some values. So all you need is to import them and make them global with global keyword.



          Example:



          >>> math
          Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
          NameError: name 'math' is not defined
          >>> def f():
          ... global math
          ... import math
          ...
          >>> f()
          >>> math
          <module 'math' from '/usr/local/lib/python2.6/lib-dynload/math.so'>





          share|improve this answer





















          • 4





            Are you sure this is legal? The docs (docs.python.org/2/reference/…) say "Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement." It then says this is not enforced for cpython, but you shouldn't do this.

            – xioxox
            Feb 17 '15 at 9:36











          • global ab.cd raise a SyntaxError

            – V Y
            Jul 18 '16 at 19:00











          • @VY, in that case you would need to use just global ab, as well, cf. my answer

            – maxschlepzig
            Oct 9 '16 at 7:56














          61












          61








          61







          Imported modules are just variables - names bound to some values. So all you need is to import them and make them global with global keyword.



          Example:



          >>> math
          Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
          NameError: name 'math' is not defined
          >>> def f():
          ... global math
          ... import math
          ...
          >>> f()
          >>> math
          <module 'math' from '/usr/local/lib/python2.6/lib-dynload/math.so'>





          share|improve this answer















          Imported modules are just variables - names bound to some values. So all you need is to import them and make them global with global keyword.



          Example:



          >>> math
          Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
          NameError: name 'math' is not defined
          >>> def f():
          ... global math
          ... import math
          ...
          >>> f()
          >>> math
          <module 'math' from '/usr/local/lib/python2.6/lib-dynload/math.so'>






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 31 '15 at 17:04

























          answered Aug 16 '12 at 15:39









          Roman BodnarchukRoman Bodnarchuk

          21.6k75170




          21.6k75170








          • 4





            Are you sure this is legal? The docs (docs.python.org/2/reference/…) say "Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement." It then says this is not enforced for cpython, but you shouldn't do this.

            – xioxox
            Feb 17 '15 at 9:36











          • global ab.cd raise a SyntaxError

            – V Y
            Jul 18 '16 at 19:00











          • @VY, in that case you would need to use just global ab, as well, cf. my answer

            – maxschlepzig
            Oct 9 '16 at 7:56














          • 4





            Are you sure this is legal? The docs (docs.python.org/2/reference/…) say "Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement." It then says this is not enforced for cpython, but you shouldn't do this.

            – xioxox
            Feb 17 '15 at 9:36











          • global ab.cd raise a SyntaxError

            – V Y
            Jul 18 '16 at 19:00











          • @VY, in that case you would need to use just global ab, as well, cf. my answer

            – maxschlepzig
            Oct 9 '16 at 7:56








          4




          4





          Are you sure this is legal? The docs (docs.python.org/2/reference/…) say "Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement." It then says this is not enforced for cpython, but you shouldn't do this.

          – xioxox
          Feb 17 '15 at 9:36





          Are you sure this is legal? The docs (docs.python.org/2/reference/…) say "Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement." It then says this is not enforced for cpython, but you shouldn't do this.

          – xioxox
          Feb 17 '15 at 9:36













          global ab.cd raise a SyntaxError

          – V Y
          Jul 18 '16 at 19:00





          global ab.cd raise a SyntaxError

          – V Y
          Jul 18 '16 at 19:00













          @VY, in that case you would need to use just global ab, as well, cf. my answer

          – maxschlepzig
          Oct 9 '16 at 7:56





          @VY, in that case you would need to use just global ab, as well, cf. my answer

          – maxschlepzig
          Oct 9 '16 at 7:56













          9














          You can make the imports global within a function like this:



          def my_imports(module_name):
          globals()[module_name] = __import__(module_name)





          share|improve this answer



















          • 1





            Also, importlib offers a wrapper for __import__ in the import_module function.

            – metakermit
            Sep 2 '14 at 13:57











          • if you do globals()['ab.cd'] = __import__('ab.cd') inside function my_imports, module ab.cd will not be imported

            – V Y
            Jul 18 '16 at 19:03











          • def my_imports(modulename,shortname = None): if shortname is None: shortname = modulename globals()[shortname] = __import__(modulename)

            – mshaffer
            Oct 22 '17 at 19:36











          • my_imports("rpy2")

            – mshaffer
            Oct 22 '17 at 19:36











          • my_imports("numpy","np")

            – mshaffer
            Oct 22 '17 at 19:36
















          9














          You can make the imports global within a function like this:



          def my_imports(module_name):
          globals()[module_name] = __import__(module_name)





          share|improve this answer



















          • 1





            Also, importlib offers a wrapper for __import__ in the import_module function.

            – metakermit
            Sep 2 '14 at 13:57











          • if you do globals()['ab.cd'] = __import__('ab.cd') inside function my_imports, module ab.cd will not be imported

            – V Y
            Jul 18 '16 at 19:03











          • def my_imports(modulename,shortname = None): if shortname is None: shortname = modulename globals()[shortname] = __import__(modulename)

            – mshaffer
            Oct 22 '17 at 19:36











          • my_imports("rpy2")

            – mshaffer
            Oct 22 '17 at 19:36











          • my_imports("numpy","np")

            – mshaffer
            Oct 22 '17 at 19:36














          9












          9








          9







          You can make the imports global within a function like this:



          def my_imports(module_name):
          globals()[module_name] = __import__(module_name)





          share|improve this answer













          You can make the imports global within a function like this:



          def my_imports(module_name):
          globals()[module_name] = __import__(module_name)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 16 '12 at 16:25









          badzilbadzil

          1,70531326




          1,70531326








          • 1





            Also, importlib offers a wrapper for __import__ in the import_module function.

            – metakermit
            Sep 2 '14 at 13:57











          • if you do globals()['ab.cd'] = __import__('ab.cd') inside function my_imports, module ab.cd will not be imported

            – V Y
            Jul 18 '16 at 19:03











          • def my_imports(modulename,shortname = None): if shortname is None: shortname = modulename globals()[shortname] = __import__(modulename)

            – mshaffer
            Oct 22 '17 at 19:36











          • my_imports("rpy2")

            – mshaffer
            Oct 22 '17 at 19:36











          • my_imports("numpy","np")

            – mshaffer
            Oct 22 '17 at 19:36














          • 1





            Also, importlib offers a wrapper for __import__ in the import_module function.

            – metakermit
            Sep 2 '14 at 13:57











          • if you do globals()['ab.cd'] = __import__('ab.cd') inside function my_imports, module ab.cd will not be imported

            – V Y
            Jul 18 '16 at 19:03











          • def my_imports(modulename,shortname = None): if shortname is None: shortname = modulename globals()[shortname] = __import__(modulename)

            – mshaffer
            Oct 22 '17 at 19:36











          • my_imports("rpy2")

            – mshaffer
            Oct 22 '17 at 19:36











          • my_imports("numpy","np")

            – mshaffer
            Oct 22 '17 at 19:36








          1




          1





          Also, importlib offers a wrapper for __import__ in the import_module function.

          – metakermit
          Sep 2 '14 at 13:57





          Also, importlib offers a wrapper for __import__ in the import_module function.

          – metakermit
          Sep 2 '14 at 13:57













          if you do globals()['ab.cd'] = __import__('ab.cd') inside function my_imports, module ab.cd will not be imported

          – V Y
          Jul 18 '16 at 19:03





          if you do globals()['ab.cd'] = __import__('ab.cd') inside function my_imports, module ab.cd will not be imported

          – V Y
          Jul 18 '16 at 19:03













          def my_imports(modulename,shortname = None): if shortname is None: shortname = modulename globals()[shortname] = __import__(modulename)

          – mshaffer
          Oct 22 '17 at 19:36





          def my_imports(modulename,shortname = None): if shortname is None: shortname = modulename globals()[shortname] = __import__(modulename)

          – mshaffer
          Oct 22 '17 at 19:36













          my_imports("rpy2")

          – mshaffer
          Oct 22 '17 at 19:36





          my_imports("rpy2")

          – mshaffer
          Oct 22 '17 at 19:36













          my_imports("numpy","np")

          – mshaffer
          Oct 22 '17 at 19:36





          my_imports("numpy","np")

          – mshaffer
          Oct 22 '17 at 19:36











          2














          You could have this function return the names of the modules you want to import, and then use



          mod == __import__(module_name)





          share|improve this answer
























          • I like the approach but your code wouldn't actually work in this case. This code just returns the module but doesn't actually put in the global variables. See my answer for how to do it.

            – badzil
            Aug 16 '12 at 19:46













          • I understand that the response doesn't quite answer the OP's question. However, I generally dislike manipulating globals(). Better to programmatically import the correct modules at the proper scope, IMO (see stackoverflow.com/a/11543718/1332492 for more ranting along these lines)

            – ChrisB
            Aug 16 '12 at 20:11
















          2














          You could have this function return the names of the modules you want to import, and then use



          mod == __import__(module_name)





          share|improve this answer
























          • I like the approach but your code wouldn't actually work in this case. This code just returns the module but doesn't actually put in the global variables. See my answer for how to do it.

            – badzil
            Aug 16 '12 at 19:46













          • I understand that the response doesn't quite answer the OP's question. However, I generally dislike manipulating globals(). Better to programmatically import the correct modules at the proper scope, IMO (see stackoverflow.com/a/11543718/1332492 for more ranting along these lines)

            – ChrisB
            Aug 16 '12 at 20:11














          2












          2








          2







          You could have this function return the names of the modules you want to import, and then use



          mod == __import__(module_name)





          share|improve this answer













          You could have this function return the names of the modules you want to import, and then use



          mod == __import__(module_name)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Aug 16 '12 at 15:28









          ChrisBChrisB

          2,71232138




          2,71232138













          • I like the approach but your code wouldn't actually work in this case. This code just returns the module but doesn't actually put in the global variables. See my answer for how to do it.

            – badzil
            Aug 16 '12 at 19:46













          • I understand that the response doesn't quite answer the OP's question. However, I generally dislike manipulating globals(). Better to programmatically import the correct modules at the proper scope, IMO (see stackoverflow.com/a/11543718/1332492 for more ranting along these lines)

            – ChrisB
            Aug 16 '12 at 20:11



















          • I like the approach but your code wouldn't actually work in this case. This code just returns the module but doesn't actually put in the global variables. See my answer for how to do it.

            – badzil
            Aug 16 '12 at 19:46













          • I understand that the response doesn't quite answer the OP's question. However, I generally dislike manipulating globals(). Better to programmatically import the correct modules at the proper scope, IMO (see stackoverflow.com/a/11543718/1332492 for more ranting along these lines)

            – ChrisB
            Aug 16 '12 at 20:11

















          I like the approach but your code wouldn't actually work in this case. This code just returns the module but doesn't actually put in the global variables. See my answer for how to do it.

          – badzil
          Aug 16 '12 at 19:46







          I like the approach but your code wouldn't actually work in this case. This code just returns the module but doesn't actually put in the global variables. See my answer for how to do it.

          – badzil
          Aug 16 '12 at 19:46















          I understand that the response doesn't quite answer the OP's question. However, I generally dislike manipulating globals(). Better to programmatically import the correct modules at the proper scope, IMO (see stackoverflow.com/a/11543718/1332492 for more ranting along these lines)

          – ChrisB
          Aug 16 '12 at 20:11





          I understand that the response doesn't quite answer the OP's question. However, I generally dislike manipulating globals(). Better to programmatically import the correct modules at the proper scope, IMO (see stackoverflow.com/a/11543718/1332492 for more ranting along these lines)

          – ChrisB
          Aug 16 '12 at 20:11











          2














          You can use the built-in function __import__ to conditionally import a module with global scope.



          To import a top level module (think: import foo):



          def cond_import():
          global foo
          foo = __import__('foo', globals(), locals())


          Import from a hierarchy (think: import foo.bar):



          def cond_import():
          global foo
          foo = __import__('foo.bar', globals(), locals())


          Import from a hierarchy and alias (think: import foo.bar as bar):



          def cond_import():
          global bar
          foo = __import__('foo.bar', globals(), locals())
          bar = foo.bar





          share|improve this answer




























            2














            You can use the built-in function __import__ to conditionally import a module with global scope.



            To import a top level module (think: import foo):



            def cond_import():
            global foo
            foo = __import__('foo', globals(), locals())


            Import from a hierarchy (think: import foo.bar):



            def cond_import():
            global foo
            foo = __import__('foo.bar', globals(), locals())


            Import from a hierarchy and alias (think: import foo.bar as bar):



            def cond_import():
            global bar
            foo = __import__('foo.bar', globals(), locals())
            bar = foo.bar





            share|improve this answer


























              2












              2








              2







              You can use the built-in function __import__ to conditionally import a module with global scope.



              To import a top level module (think: import foo):



              def cond_import():
              global foo
              foo = __import__('foo', globals(), locals())


              Import from a hierarchy (think: import foo.bar):



              def cond_import():
              global foo
              foo = __import__('foo.bar', globals(), locals())


              Import from a hierarchy and alias (think: import foo.bar as bar):



              def cond_import():
              global bar
              foo = __import__('foo.bar', globals(), locals())
              bar = foo.bar





              share|improve this answer













              You can use the built-in function __import__ to conditionally import a module with global scope.



              To import a top level module (think: import foo):



              def cond_import():
              global foo
              foo = __import__('foo', globals(), locals())


              Import from a hierarchy (think: import foo.bar):



              def cond_import():
              global foo
              foo = __import__('foo.bar', globals(), locals())


              Import from a hierarchy and alias (think: import foo.bar as bar):



              def cond_import():
              global bar
              foo = __import__('foo.bar', globals(), locals())
              bar = foo.bar






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Oct 9 '16 at 7:46









              maxschlepzigmaxschlepzig

              14.2k775107




              14.2k775107























                  1














                  I like @badzil approach.



                  def global_imports(modulename,shortname = None, asfunction = False):
                  if shortname is None:
                  shortname = modulename
                  if asfunction is False:
                  globals()[shortname] = __import__(modulename)
                  else:
                  globals()[shortname] = eval(modulename + "." + shortname)


                  So something that is traditionally in a class module:



                  import numpy as np

                  import rpy2
                  import rpy2.robjects as robjects
                  import rpy2.robjects.packages as rpackages
                  from rpy2.robjects.packages import importr


                  Can be transformed into a global scope:



                  global_imports("numpy","np")

                  global_imports("rpy2")
                  global_imports("rpy2.robjects","robjects")
                  global_imports("rpy2.robjects.packages","rpackages")
                  global_imports("rpy2.robjects.packages","importr",True)


                  May have some bugs, which I will verify and update. The last example could also have an alias which would be another "shortname" or a hack like "importr|aliasimportr"






                  share|improve this answer




























                    1














                    I like @badzil approach.



                    def global_imports(modulename,shortname = None, asfunction = False):
                    if shortname is None:
                    shortname = modulename
                    if asfunction is False:
                    globals()[shortname] = __import__(modulename)
                    else:
                    globals()[shortname] = eval(modulename + "." + shortname)


                    So something that is traditionally in a class module:



                    import numpy as np

                    import rpy2
                    import rpy2.robjects as robjects
                    import rpy2.robjects.packages as rpackages
                    from rpy2.robjects.packages import importr


                    Can be transformed into a global scope:



                    global_imports("numpy","np")

                    global_imports("rpy2")
                    global_imports("rpy2.robjects","robjects")
                    global_imports("rpy2.robjects.packages","rpackages")
                    global_imports("rpy2.robjects.packages","importr",True)


                    May have some bugs, which I will verify and update. The last example could also have an alias which would be another "shortname" or a hack like "importr|aliasimportr"






                    share|improve this answer


























                      1












                      1








                      1







                      I like @badzil approach.



                      def global_imports(modulename,shortname = None, asfunction = False):
                      if shortname is None:
                      shortname = modulename
                      if asfunction is False:
                      globals()[shortname] = __import__(modulename)
                      else:
                      globals()[shortname] = eval(modulename + "." + shortname)


                      So something that is traditionally in a class module:



                      import numpy as np

                      import rpy2
                      import rpy2.robjects as robjects
                      import rpy2.robjects.packages as rpackages
                      from rpy2.robjects.packages import importr


                      Can be transformed into a global scope:



                      global_imports("numpy","np")

                      global_imports("rpy2")
                      global_imports("rpy2.robjects","robjects")
                      global_imports("rpy2.robjects.packages","rpackages")
                      global_imports("rpy2.robjects.packages","importr",True)


                      May have some bugs, which I will verify and update. The last example could also have an alias which would be another "shortname" or a hack like "importr|aliasimportr"






                      share|improve this answer













                      I like @badzil approach.



                      def global_imports(modulename,shortname = None, asfunction = False):
                      if shortname is None:
                      shortname = modulename
                      if asfunction is False:
                      globals()[shortname] = __import__(modulename)
                      else:
                      globals()[shortname] = eval(modulename + "." + shortname)


                      So something that is traditionally in a class module:



                      import numpy as np

                      import rpy2
                      import rpy2.robjects as robjects
                      import rpy2.robjects.packages as rpackages
                      from rpy2.robjects.packages import importr


                      Can be transformed into a global scope:



                      global_imports("numpy","np")

                      global_imports("rpy2")
                      global_imports("rpy2.robjects","robjects")
                      global_imports("rpy2.robjects.packages","rpackages")
                      global_imports("rpy2.robjects.packages","importr",True)


                      May have some bugs, which I will verify and update. The last example could also have an alias which would be another "shortname" or a hack like "importr|aliasimportr"







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Oct 22 '17 at 19:52









                      mshaffermshaffer

                      3531412




                      3531412























                          1














                          I've just had the similar problem, here is my solution:



                          class GlobalImport:

                          def __enter__(self):
                          return self

                          def __call__(self):
                          import inspect
                          self.collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1].frame).locals

                          def __exit__(self, *args):
                          globals().update(self.collector)


                          then, anywhere in the code:



                          with GlobalImport() as gi:
                          import os, signal, atexit, threading, _thread
                          # whatever you want it won't remain local
                          # if only
                          gi()
                          # is called before the end of this block

                          # there you go: use os, signal, ... from whatever place of the module





                          share|improve this answer






























                            1














                            I've just had the similar problem, here is my solution:



                            class GlobalImport:

                            def __enter__(self):
                            return self

                            def __call__(self):
                            import inspect
                            self.collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1].frame).locals

                            def __exit__(self, *args):
                            globals().update(self.collector)


                            then, anywhere in the code:



                            with GlobalImport() as gi:
                            import os, signal, atexit, threading, _thread
                            # whatever you want it won't remain local
                            # if only
                            gi()
                            # is called before the end of this block

                            # there you go: use os, signal, ... from whatever place of the module





                            share|improve this answer




























                              1












                              1








                              1







                              I've just had the similar problem, here is my solution:



                              class GlobalImport:

                              def __enter__(self):
                              return self

                              def __call__(self):
                              import inspect
                              self.collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1].frame).locals

                              def __exit__(self, *args):
                              globals().update(self.collector)


                              then, anywhere in the code:



                              with GlobalImport() as gi:
                              import os, signal, atexit, threading, _thread
                              # whatever you want it won't remain local
                              # if only
                              gi()
                              # is called before the end of this block

                              # there you go: use os, signal, ... from whatever place of the module





                              share|improve this answer















                              I've just had the similar problem, here is my solution:



                              class GlobalImport:

                              def __enter__(self):
                              return self

                              def __call__(self):
                              import inspect
                              self.collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1].frame).locals

                              def __exit__(self, *args):
                              globals().update(self.collector)


                              then, anywhere in the code:



                              with GlobalImport() as gi:
                              import os, signal, atexit, threading, _thread
                              # whatever you want it won't remain local
                              # if only
                              gi()
                              # is called before the end of this block

                              # there you go: use os, signal, ... from whatever place of the module






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Oct 17 '18 at 14:25

























                              answered Oct 17 '18 at 14:11









                              rafał grabierafał grabie

                              213




                              213























                                  0














                                  I like @rafał grabie approach. As it even support importing all.
                                  i.e.
                                  from os import *



                                  (Despite it being bad practice XD )



                                  Not allowed to comment, but here is a python 2.7 version.



                                  Also removed the need to call the function at the end.



                                  class GlobalImport:
                                  def __enter__(self):
                                  return self
                                  def __exit__(self, *args):
                                  import inspect
                                  collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1][0]).locals
                                  globals().update(collector)

                                  def test():
                                  with GlobalImport() as gi:
                                  ## will fire a warning as its bad practice for python.
                                  from os import *

                                  test()
                                  print path.exists(__file__)





                                  share|improve this answer




























                                    0














                                    I like @rafał grabie approach. As it even support importing all.
                                    i.e.
                                    from os import *



                                    (Despite it being bad practice XD )



                                    Not allowed to comment, but here is a python 2.7 version.



                                    Also removed the need to call the function at the end.



                                    class GlobalImport:
                                    def __enter__(self):
                                    return self
                                    def __exit__(self, *args):
                                    import inspect
                                    collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1][0]).locals
                                    globals().update(collector)

                                    def test():
                                    with GlobalImport() as gi:
                                    ## will fire a warning as its bad practice for python.
                                    from os import *

                                    test()
                                    print path.exists(__file__)





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      I like @rafał grabie approach. As it even support importing all.
                                      i.e.
                                      from os import *



                                      (Despite it being bad practice XD )



                                      Not allowed to comment, but here is a python 2.7 version.



                                      Also removed the need to call the function at the end.



                                      class GlobalImport:
                                      def __enter__(self):
                                      return self
                                      def __exit__(self, *args):
                                      import inspect
                                      collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1][0]).locals
                                      globals().update(collector)

                                      def test():
                                      with GlobalImport() as gi:
                                      ## will fire a warning as its bad practice for python.
                                      from os import *

                                      test()
                                      print path.exists(__file__)





                                      share|improve this answer













                                      I like @rafał grabie approach. As it even support importing all.
                                      i.e.
                                      from os import *



                                      (Despite it being bad practice XD )



                                      Not allowed to comment, but here is a python 2.7 version.



                                      Also removed the need to call the function at the end.



                                      class GlobalImport:
                                      def __enter__(self):
                                      return self
                                      def __exit__(self, *args):
                                      import inspect
                                      collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1][0]).locals
                                      globals().update(collector)

                                      def test():
                                      with GlobalImport() as gi:
                                      ## will fire a warning as its bad practice for python.
                                      from os import *

                                      test()
                                      print path.exists(__file__)






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 12 '18 at 4:00









                                      JanJan

                                      315




                                      315






























                                          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%2f11990556%2fhow-to-make-global-imports-from-a-function%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







                                          這個網誌中的熱門文章

                                          Academy of Television Arts & Sciences

                                          L'Équipe

                                          1995 France bombings