python3 --- locale命名空间让程序更加安全了

简介

  由于python-2.x 并没有locale这个层次的命名空间,所以临时变量有可能会泄漏,进而影响到了包涵它的命名空间

 

看一下pyhont-2.x是怎么泄漏临时变量的

python
Python 2.7.10 (default, Aug 17 2018, 17:41:52) 
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 100
>>> s = [x for x in range(10) ]
>>> x
9
>>>

  可以看到列表推导中用的临时变量x泄漏导致变局命名空间中的x被污染

 

看一下python-3的情况

python3
Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 100
>>> s = [x for x in range(10) ]
>>> x
100

  可以看到临时变量并没能污染到全局变量、多亏了python-3的locale命名空间

 

总结

  由于 python2 ~ python3 多出了一个locale命名空间,影响是非常深远的;编写代码的时候要多加小心。 

---

posted on 2019-01-27 12:38  蒋乐兴的技术随笔  阅读(314)  评论(0编辑  收藏  举报

导航