I'm doing
module = __import__("client.elements.gui.button", globals(), locals(), [], 0)
But it's only returning client
.
What is my problem?
I'm doing
module = __import__("client.elements.gui.button", globals(), locals(), [], 0)
But it's only returning client
.
What is my problem?
That's what __import__
does.
You're not really supposed to use __import__
; if you want to import a module dynamically, use importlib.import_module
.
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.
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