5

Possible Duplicate:
from . import x using __import__?
How does one do the equivalent of import * from module with Python's __import__ function?

How would I do the from ... import * with the __import__ function? The reason being that i only know the name of the file at runtime and it only has 1 class inside that file.

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59
Pwnna
  • 9,178
  • 21
  • 65
  • 91

2 Answers2

6

In case someone reading this wants an actual answer to the question in the title, you can do it by manipulating the vars() dictionary. Yes, it is dumb to do this in most scenarios, but I can think of use cases where it would actually be really useful/cool (e.g. maybe you want a static module name, but want the contents of the module to come from somewhere else that's defined at runtime. Similar to and, IMO, better than the behavior of django.conf.settings if you're familiar with it)

module_name = "foo"
for key, val in vars(__import__(module_name)).iteritems():
    if key.startswith('__') and key.endswith('__'):
        continue
    vars()[key] = val

This imports every non-system variable in the module foo.py into the current namespace.

Use sparingly :)

danny
  • 10,103
  • 10
  • 50
  • 57
3

Don't. Just don't. Do I need to explain just how horrible that it? Dynamically importing (though sometimes inevitable) and importing into global namespace (always avoidable, but sometimes the easier solution and fine withtrusted modules) are bad enough themselves. Dynamically importing into global namespace is... a nightmare (and avoidable).

Just do _temp = __import__(name, globals(), locals(), [name_of_class]); your_class = _temp.name_of_class. According to the docs, this is about what from name import name_of_class would do.

  • ya i got that too after looking at the docs. It didn't work at first, the reason for that is i forgot to declare the your_class as global. Thanks anyway – Pwnna Jul 22 '10 at 20:01
  • 1
    so in short, you say to use `my_class = __import__(name, globals(), locals(), [name_of_class]).name_of_class` – Nas Banov Jul 22 '10 at 21:14
  • 1
    This doesn't actually answer the question. The answer below is much better. – monokrome Jun 25 '15 at 01:14