[Python] How to filter variables for import in Python

Discussão em 'Python' iniciado por Stack, Fevereiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    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 load.py and the second is 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

    Continue reading...

Compartilhe esta Página