0

Given the following folder structure:

executioner/:
  - executioner.py
  - library/:
    - __init__.py
    - global_functions.py
    - oakalleyit.py

If I wanted to access a function inside of either global_functions.py or oakalleyit.py, but I won't know the name of the function or module until runtime, how would I do it?

Something like:

from library import 'oakalleyit'

'oakalleyit'.'cleanup'()

Where the '' implies it came from a config file, CLI argument, etc.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Soviero
  • 1,774
  • 2
  • 13
  • 23

1 Answers1

3

You can use the getattr() function to access names dynamically; this includes module objects:

import library
getattr(library, 'oakalleyit')()

Demo with the hashlib module:

>>> import hashlib
>>> getattr(hashlib, 'md5')()
<md5 HASH object @ 0x1012a02b0>
>>> getattr(hashlib, 'sha1')()
<sha1 HASH object @ 0x1012a03f0>

If you need to dynamic module access, you'll need to use the importlib.import_module() function to import modules based on a string value:

from importlib import import_module

module = import_module('library.oakalleyit')
getattr(module, 'some_function_name')()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Traceback (most recent call last): File "executioner.py", line 5, in getattr(library, 'oakalleyit') AttributeError: 'module' object has no attribute 'oakalleyit' – Soviero Sep 19 '14 at 20:53
  • Despite what he says, his example suggests he needs to access a dynamically-determined module, not a function. This won't work unless `library`'s `__init__.py` auto-imports all its submodules. – BrenBarn Sep 19 '14 at 20:53
  • @BrenBarn That won't work, multiple files under 'library' may have the same function names that do different things. – Soviero Sep 19 '14 at 20:55
  • @BrenBarn Sorry, just corrected, meant multiple modules with the same function names. – Soviero Sep 19 '14 at 20:57
  • I don't think you can use `import_module` that way. You'll need to do `import_module('library.oakalleyit')` or `import_module('.oakalleyit', 'library')`. – BrenBarn Sep 19 '14 at 21:02
  • @BrenBarn: ick, you are indeed correct. – Martijn Pieters Sep 19 '14 at 21:05