Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using variable in import command

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
like image 285
madhu131313 Avatar asked Nov 01 '13 10:11

madhu131313


People also ask

Why import * is not good?

Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import.

What is __ name __ when imported?

__name__ is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement, as shown below.

What are different 3 ways to import modules?

The 4 ways to import a module Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd. Import specific things from the module and rename them as you're importing them: pycon from os. path import join as join_path.


2 Answers

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.

like image 66
Ashwini Chaudhary Avatar answered Oct 29 '22 02:10

Ashwini Chaudhary


You can use the __import__ function:

k = 'os'
module = __import__(k)
like image 38
RemcoGerlich Avatar answered Oct 29 '22 03:10

RemcoGerlich