1

I am trying to import a list from a file in python , and i don't know the name of the list or the file .

I am asking them in the code , and when I get them , i am trying to import the list ,

def listIMP(ITEM):
    listIMP = "from {0} import {1}".format(ITEM[0],', '.join(str(i) for i in ITEM[1:])) # generating command
    exec(listIMP) #exec generated command

I call it :

listN = input('!\n')# asking for list name
name = input('>') # asking for file name
name = name[:-3] #deleting .py
list1 = [name, listN] 
listIMP(list1) # calling my func

But i can't get the output , of exec , which is my list , i know i can get it as string but i would like to get it as list , is that possible ?

  • Does this answer your question? [How to import a module given its name as string?](https://stackoverflow.com/questions/301134/how-to-import-a-module-given-its-name-as-string) – Tomerikoo Oct 26 '20 at 20:51
  • your function runs `exec` with the default parameters. This passes `globals()` and `locals()` to their respective arguments. However, modifications to `locals()` will *not affect the actual local namespace*. There is almost certainly a better way, like using `imporlib` to import the module. – juanpa.arrivillaga Oct 26 '20 at 20:52
  • Note, imports inside a local scope only add names *to that local scope*. Your function with a hard-coded import statement wouldn't work the way you seem to desire for it to work anyway – juanpa.arrivillaga Oct 26 '20 at 20:53

1 Answers1

5

Try import_module() with getattr() instead:

from importlib import import_module

def import_from(module, variable):
    return getattr(import_module(module), variable)

print(import_from('module_name', 'variable_name'))

exec() was not exactly made for what you're trying to achieve. Using it here will give you unnecessary headaches.

You might also find JSON useful: see json module.

Edit: replaced __import__() with import_module(). Usage of the former is discouraged.

Błażej Michalik
  • 4,474
  • 40
  • 55