[Python] One-liner to specify many variables for "del" and ignore those that don't exist

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am using Spyder for exploratory data analysis -- not for production code. I like to think of my script as a sequence of major sections. At the end of each section, I want to delete the temporary objects so that the Variable Explorer in Spyder isn't too crowded. However, the objects that exist depend on the control flow through the code. If I have just one del statement at the end of each section to delete all objects that may come into existence regardless of the control flow through the code, I get NameError for those objects that haven't been created.

    Is there a simple one-liner that I can use, similar to del a,b,c,d but not yielding an error if some of the variables don't exist? I want a short one-liner because I don't want to take attention away from the main functions of the code.

    A try/except block is a multi-line control structure that contributes too much cognitive noise to the code, in my opinion. Something like the following doesn't seem legal, and it seems to be that a one-liner can't consist of an if-statement within a for-loop:

    # Syntax error at the "if"
    for vName in ['gbCluster']: if vName in locals(): del locals()[vName]

    # Works without "if"
    for vName in ['gbCluster']: del locals()[vName]

    Continue reading...

Compartilhe esta Página