9

I am trying to import a module from inside a function and have it be available to my whole file the same way it would be if I imported outside any functions and before all the other code. The reason it is in a function is because I don't have much control over the structure of the script. Is this possible without resorting to things like hacking __builtin__ or passing what I need all around my code?

scott77777
  • 608
  • 2
  • 7
  • 17
  • 2
    Don't do that if you care about the next person who has to read your code (probably yourself). It sounds like you are using poor organizational practice as an excuse for poor coding practice; try to fix the root cause. – msw Jun 14 '11 at 17:35
  • 1
    I am modifying an open source project and attempting to change the absolute minimum necessary. – scott77777 Jun 14 '11 at 17:36
  • 3
    So by trying to change the minimum necessary, you'll make it incomprehensible to all other contributors. That's a poor trade-off. – msw Jun 14 '11 at 17:43
  • 1
    If it were up to me I would restructure many parts of the code, but my boss doesn't want me to. EDIT: to make it a bit clearer, the module name is not known until this point in the code, which is why I am looking to import it here in the first place. Importing at the top isn't what we consider to be too much of a change. – scott77777 Jun 14 '11 at 17:51

2 Answers2

9

How about something like globals()["os"] = __import__("os")?

I guess this could be wrapped in a generic function if you wanted since the module name is a string.

jkp
  • 70,446
  • 25
  • 98
  • 102
  • This is good because the index can be used to emulate the "import as" behavior that is not (I believe) built in to `__import__()`. It turns out that this does not solve my problem, but it does answer the question I asked. – scott77777 Jun 14 '11 at 18:10
7

Seeing your new comments, I want to emphasize that this sounds unnecessary. You're actually modifying the script more by importing within a function than by importing at the top of the script in the normal way. Still, in the spirit of answering the question asked, I'm leaving my previous answer.


I'm honestly not certain this is the correct way to do this, but a quick check confirms that if you declare the module name as global within the function before importing, it is imported into the global namespace.

>>> def import_re():
...     global re
...     import re
... 
>>> re
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 're' is not defined
>>> import_re()
>>> re
<module 're' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.pyc'>

Don't do this unless you really have to -- and then write it in big red letters, so to speak.

senderle
  • 125,265
  • 32
  • 201
  • 223