Maison > Article > développement back-end > Python没有常量是不是不够安全的设计?
我是一个Python轻度用户+爱好者,这两天我尝试用Python替代bash完成一些简单的工作(最主要的目的其实是学习),有一些困惑。
Python不能很方便的定义常量,这就带来了一些问题,如果一个程序或引用的第三方库,不小心修改了某一个模块下的一个全局变量,比如re模块的re.I,re.M等,这样就会给程序带来很大的不确定性?
re这个例子只不过是一个历史遗留问题,是特例,还是类似的例子在Python中是普遍存在的?
<code class="language-python"><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">namedtuple</span>
<span class="k">def</span> <span class="nf">const</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="n">ConstType</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s">"Constant"</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="k">return</span> <span class="n">ConstType</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="n">const1</span> <span class="o">=</span> <span class="n">const</span><span class="p">(</span>
<span class="n">name</span><span class="o">=</span><span class="s">"test"</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="mi">123</span><span class="p">,</span>
<span class="p">)</span>
<span class="k">print</span> <span class="n">const1</span><span class="o">.</span><span class="n">name</span> <span class="c"># test</span>
<span class="n">const1</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s">"xxxx"</span> <span class="c"># raise AttributeError</span>
</code>
别作死…………<code class="language-python"><span class="bp">True</span><span class="p">,</span> <span class="bp">False</span> <span class="o">=</span> <span class="bp">False</span><span class="p">,</span> <span class="bp">True</span>
</code>
全局变量可以有,但是如果滥用就不好了。考虑你问题的规模,小脚本还好说,如果依赖复杂,大量依赖全局变量,我觉得设计本身可能就有问题。