Search code examples
pythondynamicpython-module

Pythonic way to import module whose name is only known at runtime?


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.


Solution

  • 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')()