pythonpython-3.ximportpython-import

How to filter variables for import in Python


I really need to solve my problem because one of the scripts I built, there are hundreds of variables; and in the other script, I don't want to import all variables but only specific variables using Regex; but it seems there is no way how to do.

I'll give an example, there are two scripts, the first one is script_load.py and the second is script_main.py

script_load.py

import os
from configparser import ConfigParser

file = os.path.join(os.getcwd(), 'file.txt')
fparser = ConfigParser()
fparser.read(file)
COLOUR_ONE = fparser.get("GENERAL", "Green")
COLOUR_TWO = fparser.get("GENERAL", "Red")
COLOUR_THREE = fparser.get("GENERAL", "Blue")
BUILDING_ONE = fparser.get("GENERAL", "House")
BUILDING_TWO = fparser.get("GENERAL", "School")
BUILDING_THREE = fparser.get("GENERAL", "Supermarket")

script_main.py

from script_load import r'^COLOUR.+$'

def function():
    global r'^COLOUR.+$'

    print(COLOUR_ONE+COLOUR_TWO+COLOUR_THREE)

As the above, I want to use a syntax like import r'^COLOUR.+$' instead of import * to filter variables as imported. However, I tested and it got error as the following output:

SyntaxError: invalid syntax

Note: What I want is to use the same variables in script_main.py as in script_load.py, not to create new variables because in my problem as I said at the beginning, there are hundreds of variables and I don't want to fill up new variables in script_main.py, besides to import all variables from script_load.py into script_main.py, some of variables could be combined and it will not work fine; So, the post "How can I import a module dynamically given its name as string?" as someone suggested me, it doesn't work me.


Solution

  • You can probably do it with importlib and then adding the variables to the global scope:

    import importlib
    import re
    
    
    def dynamic_import(pattern: re.Pattern, name: str) -> None:
        module = importlib.import_module(name)
    
        for attr in dir(module):
            match = pattern.match(attr)
            if not match:
                continue
    
            globals()[attr] = getattr(module, attr)
        del module
    
    
    dynamic_import(re.compile('COLOUR_.*'), 'script_load')
    
    print(dir())  # show the variables in global namespace