6

I have a variable like

k = os

If I have to import os I can write

import os

then I get no error But how can I import k ( k is actually os ) I tried

import k

then I got error there is no module. I tried naming k = 'os' instead of k = os.Still I am getting the same error

Update : Actually I have to import DATABASES variable from settings file in the environmental variable DJANGO_SETTINGS_MODULE

How can I achieve this

from os.environ['DJANGO_SETTINGS_MODULE'] import DATABASES
3
  • 2
    You can't use variable names in import statements. Commented Nov 1, 2013 at 10:43
  • Any good reason to use variables? Commented Nov 1, 2013 at 10:45
  • 2
    I do not understand why to downvote a reasonable question. Commented Nov 1, 2013 at 12:32

2 Answers 2

7

Use importlib module if you want to import modules based on a string:

>>> import importlib
>>> os = importlib.import_module('os')
>>> os
<module 'os' from '/usr/lib/python2.7/os.pyc'>

When you do something like this:

>>> k = 'os'
>>> import k

then Python still looks for file named k.py, k.pyc etc not os.py as you intended.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any reason to prefer importlib.import_module over the simpler __import__?
@MarkRansom For simple import you could use __import__ as well, but it is recommended(help(__import__)) to use importlib.import_module module. But when importing packages they differ slightly.
3

You can use the __import__ function:

k = 'os'
module = __import__(k)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.