3

I can't use this

import foo
method_to_call = getattr(foo, 'bar')
result = method_to_call()

because module name is hardcoded and I can't use this

module = __import__('foo')
func = getattr(module, 'bar')
func()

because module is nested.

I tried this

customer = 'jci'
module = __import__('customer.{customer_name}.gt'.format(customer_name=customer_name)) # AttributeError: module 'customer' has no attribute 'get_gt'
#module = __import__('customer.{customer_name}'.format(customer_name=customer_name), fromlist=['gt']) # AttributeError: module 'customer.jci' has no attribute 'get_gt'
#module = __import__('customer.{customer_name}.gt'.format(customer_name=customer_name), fromlist=[]) # AttributeError: module 'customer' has no attribute 'get_gt'
func = getattr(module, 'get_gt')
gt = func() 

but failed with errors, specified in comment along with each variant.

get_gt() is a function inside gt.py file inside customer/jci directory. Each directory has empty __init__.py inside.

The following hardcoded code works:

import customer.jci.gt as g
gt = g.get_gt()

How to overcome?

asked Dec 12, 2018 at 14:23

1 Answer 1

3

What you want is importlib.import_module.


Note that __import__ does handle dotted names but it returns the parent package, not the last child.

Proof:

>>> http = __import__('http.client')
>>> http.client # the client submodule was imported
<module 'http.client' from '/usr/lib/python3.6/http/client.py'>
>>> # without specifying the .client in the name the submodule is not imported
>>> __import__('http').client
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: module 'http' has no attribute 'client'

import_module instead returns the child module, which is what most people expect:

>>> importlib.import_module('http.client')
<module 'http.client' from '/usr/lib/python3.6/http/client.py'>
answered Dec 12, 2018 at 14:32
Sign up to request clarification or add additional context in comments.

3 Comments

This is a good approach, anyway if his package has a class and he wants the method from class, he will return to initial case.
@MauroBaraldi I don't understand what you are saying. There is no one function where you can specify package.module.class.method and get a reference to the method. The OP already knows how to retriever an attribute using getattr, the only issue they had is the one I explained in the answer.
You're right @Bakuriu, I have misunderstood the question. Sorry :-(

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.