Dynamically import the called, given the full path to the module?

>>> import_path('os.path.join')
<function join at 0x22d4050>

What is the easiest way to write import_path(in Python 2.6 and above)? Suppose the last component is always callable in a module / package.

+3
source share
3 answers

This is similar to what you want:

def import_path(name):
    modname, _, attr = name.rpartition('.')
    if not modname:
        # name was just a single module name
        return __import__(attr)
    m = __import__(modname, fromlist=[attr])
    return getattr(m, attr)

To make it work with Python 2.5 and earlier, where it __import__does not accept keyword arguments, you will need to use:

m = __import__(modname, {}, globals(), [attr])
+4
source

Try

def import_path(name):
  (mod,mem) = name.rsplit('.',1)
  m = __import__(mod, fromlist=[mem])
  return getattr(m, mem)

Works at least for

>>> import_path('os.walk')
<function walk at 0x7f23c24f8848>

and now

>>> import_path('os.path.join')
<function join at 0x7f7fc7728a28>
0
source

Apparently the following works:

>>> p = 'os.path.join'
>>> a, b = p.rsplit('.', 1)
>>> getattr(__import__(a, fromlist=True), b)
<function join at 0x7f8799865230>
0
source

Source: https://habr.com/ru/post/1730903/


All Articles