[Python] Run `del variable`, to delete global variables, within Python function?

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

  1. Stack

    Stack Membro Participativo

    I'm trying write a function that will delete variables given a list of strings of those variables' names. I'm trying this:

    def delVars(ts):
    for s in ts:
    st = "del %s" % s
    print(st)
    try:
    exec(st, globals(), locals())
    except Exception as e:
    print(e)


    But except is always thrown: name 'var_name' is not defined, presumably because it's out-of-scope.

    But why is this? I'm passing globals() to exec(), so it has access to variables outside the function scope.

    Continue reading...

Compartilhe esta Página