[Python] How to create global variables dynamically from base class defined in a separate file?

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    My real scenario needs to create global variables dynamically from within a function defined in a library so it can be reused for many projects. The function can be either a method in a base class or a global function.

    For the sake of simplicity, consider the following a trivial example. I know the global variables are in file or module scope.

    # mylib.py
    class Parent:
    def __init__(self, var_name):
    self.__var_name__ = var_name
    def create_global_variable(self, var_value):
    globals()[self.__var_name__] = var_value
    def clear_global_variables(self):
    globals().clear()


    # test.py
    from mylib import Parent
    class Child(Parent): pass
    child = Child('temperature')
    child.create_global_variable(100)
    print(temperature) # NameError: name 'temperature' is not defined
    child.clear_global_variables()



    Is there any trick to bypass the restriction?

    Edit


    job() will be reused in many projects.

    def job(input, predicate, buffer_name):
    globals()[buffer_name] = predicate(input)
    return input


    exp = fr"""
    Squaring {job(2,lambda x: x*x, 'square')} equals to {square}
    """

    print(exp)


    Constraint: all buffering variables must be defined in f-string.

    Continue reading...

Compartilhe esta Página