3

I'm doing

module = __import__("client.elements.gui.button", globals(), locals(), [], 0)

But it's only returning client.

What is my problem?

Name McChange
  • 2,750
  • 5
  • 27
  • 46
  • 2
    For Python 2.7 or newer, use [`importlib.import_module()`](http://docs.python.org/2/library/importlib.html#importlib.import_module). – Martijn Pieters Dec 18 '13 at 00:01

3 Answers3

6

That's what __import__ does.

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name.

You're not really supposed to use __import__; if you want to import a module dynamically, use importlib.import_module.

user2357112
  • 260,549
  • 28
  • 431
  • 505
3

Accepted answer is correct, but if you read on in the docs you'll find that this can be gotten around with an admittedly unsettling "hack" by using __import__ like so:

module = __import__('client.elements.gui.button', fromlist=[''])

It doesn't really matter what you pass in for fromlist so long as it's a non-empty list. This signals to the default __import__ implementation that you want to do a from x.y.z import foo style import, and it will return the the module you're after.

As stated you should use importlib instead, but this is still a workaround if you need to support Python versions < 2.7.

Iguananaut
  • 21,810
  • 5
  • 50
  • 63
2

It only obtains the top level, but you can also work around this like so:

module_name = 'some.module.import.class'
    module = __import__(module_name)
    for n in module_name.split('.')[1:]:
        module = getattr(module, n)

# module is now equal to what would normally 
# have been retrieved where you to properly import the file
Mike McMahon
  • 7,096
  • 3
  • 30
  • 42