0

This is a very beginners question.

I have code with error message:

a = "sqlite3"
b = pandas
import a
import b

How to change the code, but NOT use import sqlite3 or import pandas, to get the correct results? Thanks.

doglas
  • 105
  • 1
  • 13
  • I'm really really curious about why you want to do this. Please tell. – klutt Mar 20 '17 at 18:31
  • @klutt well, I was thinking how to make the codes with less import lines... Beginners think oft strange things. :-) – doglas Mar 20 '17 at 18:37
  • I see. 'Because I can' is always a valid reason. But I had a hard time finding any actual use. – klutt Mar 20 '17 at 18:39
  • Think of your `import` statements more as documentation than as code that could (let alone should) be refactored. – chepner Mar 20 '17 at 18:54

2 Answers2

2

You can use importlib, but I would think strongly about why you would need to do this.

import importlib

# Equivalent to import sqlite3 as somemodule
a = "sqlite3"
somemodule = importlib.import_module(a)
chepner
  • 497,756
  • 71
  • 530
  • 681
2

If you do not have a very, very solid reason to import from a string, don't do it. It's a bad idea. Try to rework your code so that your script knows what libraries it needs to use. I don't know what you intend to do, but it's probably better to import both libraries and leave one unused rather than trying to import from a string.

People who really need this can try:

importlib.import_module('string')

credit to gecco for his answer in import module from string variable

Community
  • 1
  • 1