I have a function called prepared_db in submodule db.db_1:
from spam import db
submodule_name = "db_1"
func_name = "prepare_db"
func = ...
how can I get the function by the submodule name and function name in the context above?
UPDATE:
To respond @histrio 's answer, I can verify his code works for os module. But it does not work in this case. To create the example:
$ mkdir -p spam/db
$ cat > spam/db/db_1.py
def prepare_db():
print('prepare_db func')
$ touch spam/db/__init__.py
$ PYTHONPATH=$PYTHONPATH:spam
now, you can do the import normally:
>>> from spam.db.db_1 import prepare_db
>>> prepare_db()
prepare_db func
but if you do this dynamically, I get this error:
>>> getattr(getattr(db, submodule_name), func_name)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-1b6aa1216551> in <module>()
----> 1 getattr(getattr(db, submodule_name), func_name)
AttributeError: module 'spam.db.db_1' has no attribute 'prepared_db'
It's simple. You can consider module as object.
import os
submodule_name = "path"
func_name = "exists"
submodule = getattr(os, submodule_name)
function = getattr(submodule, func_name)
function('/home') # True
or [just for fun, don't do that]
fn = reduce(getattr, ('sub1', 'sub2', 'sub3', 'fn'), module)
UPDATE
import importlib
submodule = importlib.import_module('.'+submodule_name, module.__name__)
function = getattr(submodule, func_name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With