简体   繁体   中英

Is using globals() or locals() to avoid the creation of a rarely needed variable a good idea?

I have a script that processes folders. A few folders (say 5% of them) have a special status assigned to them based on their content. I use a variable special = True to store this status, which later needs to be evaluated with an if statement and an extra operation needs to be carried out just for the folders that have this marker (95% of them don't have it, in the case of which the operation is just skipped).

Now the way I understand it, a basic and simple way to do this would be:

if xxxx:
    special = True #for these few folders
else:
    special = False #for all other folders
...
if special == True:
    [operation]...

Now my problem with this is that the variable is created needlessly for 95% of the folders that do not need this marker; however, I need the variable to exist (so it must be created even if the value is False) to be able to make the evaluation because otherwise the if statement will throw an exception. So instead I use this solution:

if xxxx:
    special = True #for these few folders
...
if 'special' in globals():
    [operation]...

In this case the unnecessary variable is not created in 95% of the cases, as the variable special will only exist in the namespace if the marker was needed in the first place.

Is this good practice or is this stupid practice and making an effort this way to avoid creating a variable is overkill, makes the code downright worse, less readable, non-Pythonic, etc.? Any thoughts are appreciated.

这是矫枉过正,使代码变得更糟,可读性差,非 Pythonic 等。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM