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.

2
  • Your file structure indicates you are trying to access a module whose name you don't know (one of the two .py files), not just a function. Commented Sep 19, 2014 at 20:52
  • @BrenBarn That is exactly the case. Commented Sep 19, 2014 at 20:55

1 Answer 1

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')()
Sign up to request clarification or add additional context in comments.

6 Comments

Traceback (most recent call last): File "executioner.py", line 5, in <module> getattr(library, 'oakalleyit') AttributeError: 'module' object has no attribute 'oakalleyit'
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 That won't work, multiple files under 'library' may have the same function names that do different things.
@BrenBarn Sorry, just corrected, meant multiple modules with the same function names.
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').
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.