简体   繁体   English

使用 globals() 或 locals() 来避免创建很少需要的变量是个好主意吗?

[英]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.一些文件夹(比如其中的 5%)根据其内容分配了特殊状态。 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).我使用变量special = True来存储此状态,稍后需要使用if语句对其进行评估,并且需要仅对具有此标记的文件夹执行额外的操作(其中 95% 没有,在该操作被跳过的情况下)。

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;现在我的问题是,对于 95% 不需要此标记的文件夹,不必要地创建了该变量; 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.但是,我需要变量存在(因此即使值为 False 也必须创建它)才能进行评估,否则 if 语句将引发异常。 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.在这种情况下,在 95% 的情况下不会创建不必要的变量,因为如果首先需要标记,则变量special将仅存在于命名空间中。

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.?这是好的做法还是愚蠢的做法,并以这种方式努力避免创建变量是矫枉过正,使代码变得更糟,可读性降低,非 Pythonic 等? Any thoughts are appreciated.任何想法表示赞赏。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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