Berk Erdemoglu
Berk Erdemoglu

Reputation: 29

How to import names that start with a certain prefix from a module?

I'm building a GUI in Python.

I want to store the settings for the GUI in a separate module called settings.py. This settings module also contains some other variables/classes. But the GUI has settings that start with L_. I want to import from settings.py all the names that start with L_.

How would I go about doing that?

Upvotes: 0

Views: 387

Answers (1)

martineau
martineau

Reputation: 123463

Although dynamically defining variables is generally considered bad form, this might be an exception, so here's how to do it:

import sys

def import_names(module, prefix, namespace=None):
    """ Utility to add names with the given prefix string to given namespace.
        Default namespace is the caller's globals.
    """
    if namespace is None:
        namespace = sys._getframe(1).f_globals  # caller's globals

    for name, value in vars(settings).items():
        if name.startswith(prefix):
            print(f'adding {name} -> {value!r}')
            namespace[name] = value


if __name__ == '__main__':
    import settings
    import_names(settings, 'L_')

Upvotes: 1

Related Questions