0

Assume you have module foo and object bar. Usually you simply import object from module by doing:

from foo import bar

this is simple and straightforward. I want to accomplish same thing programatically. Name of the object "bar" is provided by the user, and can be some arbitrary value, so I need something like:

eval("from foo import %s" % ("bar"))

I'd just like to get a way to accomplish this. For some reason:

eval("from string import lower")

gives me syntaxerror.

I'm aware of some security consideration here (someone may import something stupid etc, break stuff etc). For the time being we can leave security consideration aside. I just want to import object from module and use this object later. Assuming the module name is string and the object I need to get is function lower() I need something like this:

import imp
f, filename, rest = imp.find_module("string")
my_module = imp.load_module("string", f, filename, rest)
object_i_need = my_module.load_object_from_module("lower", my_module)
object_i_need("HALLO") # should return "hallo"

Third line is missing at the moment, there is no load_object_from_module function, or I haven't found it yet.

Any suggestions are welcome.

Pawel Miech
  • 7,742
  • 4
  • 36
  • 57

2 Answers2

1

You can use __import__ with Ashwini's idea:

module = __import__("foo")
obj = getattr(module, "bar")

See __import__ reference here.

Edit: As pointed by @LukasGraf is better practice use importlib.import_module.

import importlib
module = importlib.import_module("foo")
obj = getattr(module, "bar")
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
  • 1
    You should use [`importlib.import_module`](https://docs.python.org/2/library/importlib.html#importlib.import_module), not `__import__`, unless you handle namespace packages yourself. – Lukas Graf Aug 08 '14 at 13:52
-2

You're looking for the exec statement. Brackets are optional, and it works with string formatting and concatenation, so all of the following work:

exec "from string import lower"            # Works
exec "from string import %s" % ("lower")   # Also works

exec("from string import lower")           # Also works
exec("from string import %s" % ("lower"))  # Also works

obj = "lower"
exec "from string import " + obj           # Also works
exec("from string import " + obj)          # Also works

Eval only takes an expression, not a statement, and import is a statement in python. For more on the difference between the two, https://stackoverflow.com/a/2220790/3681392

For more on the difference between expressions and statements, read the python docs: https://docs.python.org/2/reference/simple_stmts.html or search SO, there are plenty of questions about the difference.

Community
  • 1
  • 1
zaxvo
  • 186
  • 1
  • 10