Search code examples
pythonglobal-variables

How to have a very local global variable?


I find very often I have to reset some global variable, which is, otherwise just read.

I thus end up with the following snippet:

if condition:
    global _global
    _global = None

Is it possible to achieve something like:

if condition:
    global._global = None

What I'm trying to do is to restrict the "global" prefix to a single statement.

Note: in this specific case the two statements are absolutely equivalent because if already creates a local scope, bu that's not true if the code is in larger unit.

Is this "pythonycally acceptable" or I'm being carried away by my "previous life"?


Solution

  • You can use del keyword and globals() like this:

    del globals()["_global"]